Unix Socket - Structures

Various structures are used in Unix Socket Programming to hold information about the address and port, and other information. Most socket functions require a pointer to a socket address structure as an argument. Structures defined in this chapter are related to Internet Protocol Family.

sockaddr

The first structure is sockaddr that holds the socket information:

struct sockaddr{
unsigned short sa_family;
char sa_data[14];
};

This is a generic socket address structure, which will be passed in most of the socket function calls. The following table provides a description of the member fields:

Attribute

Values

Description

sa_family

AF_INET

AF_UNIX

AF_NS

AF_IMPLINK

It represents an address family. In most of the Internet-based applications, we use AF_INET.

sa_data

Protocol-specific Address

The content of the 14 bytes of protocol specific address are interpreted according to the type of address. For the Internet family, we will use port number IP address, which is represented by sockaddr_in structure defined below.

sockaddr in

The second structure that helps you to reference to the socket's elements is as follows:

This is the official name of the service. For example, SMTP, FTP POP3, etc.

s_aliases

ALIAS

It holds the list of service aliases. Most of the time this will be set to NULL.

s_port

80

It will have associated port number. For example, for HTTP, this will be 80.

s_proto

TCP

UDP

It is set to the protocol used. Internet services are provided using either TCP or UDP.

Tips on Socket Structures

Socket address structures are an integral part of every network program. We allocate them, fill them in, and pass pointers to them to various socket functions. Sometimes we pass a pointer to one of these structures to a socket function and it fills in the contents.

We always pass these structures by reference (i.e., we pass a pointer to the structure, not the structure itself), and we always pass the size of the structure as another argument.

When a socket function fills in a structure, the length is also passed by reference, so that its value can be updated by the function. We call these value-result arguments.

Always, set the structure variables to NULL (i.e., '\0') by using memset() for bzero() functions, otherwise it may get unexpected junk values in your structure.