Socket Programming Question:

Download Job Interview Questions and Answers PDF

What this function bind() does?

Socket Programming Interview Question
Socket Programming Interview Question

Answer:

Giving a Socket a Name - bind()

#include <sys/types.h>
#include <sys/socket.h>

int bind(int s, struct sockaddr *name, int namelen)

Recall that, using socketpair(), sockets could only be shared between parent and child processes or children of the same parent. With a name attached to the socket, any process on the system can describe (and use) it.

In a call to bind(), s is the file descriptor for the socket, obtained from the call to socket(). name is a pointer to a structure of type sockaddr. If the address family is AF_UNIX (as specified when the socket is created), the structure is defined as follows:


struct sockaddr {
u_short sa_family;
char sa_data[14];
};

name.sa_family should be AF_UNIX. name.sa_data should contain up to 14 bytes of a file name which will be assigned to the socket. namelen gives the actual length of name, that is, the length of the initialized contents of the data structure.
A value of 0 is return on success. On failure, -1 is returned with errno describing the error.

Example:

struct sockaddr name;
int s;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/sock");
if((s = socket(AF_UNIX, SOCK_STREAM, 0) < 0)
{
printf("socket create failure %dn", errno);
exit(0);
}
if (bind(s, &name, strlen(name.sa_data) +
sizeof(name.sa_family)) < 0)
printf("bind failure %dn", errno);

Download Socket Programming Interview Questions And Answers PDF

Previous QuestionNext Question
What this function socket() does?What this function connect() does?