Socket Programming Question:
Download Job Interview Questions and Answers PDF
What this function connect() does?
Answer:
Specifying a Remote Socket - connect()
#include <sys/types.h>
#include <sys/socket.h>
int connect(int s, struct sockaddr *name, int namelen)
The bind() call only allows specification of a local address. To specify the remote side of an address connection the connect() call is used. In the call to connect, s is the file descriptor for the socket. name is a pointer to a structure of type sockaddr:
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
As with the bind() system call, 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. A return value of 0 indicates success, while a value of -1 indicates failure with errno describing the error.
A sample code fragment:
struct sockaddr name;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/sock");
if (connect(s, &name, strlen
(name.sa_data) +
sizeof(name.sa_family)) < 0) {
printf("connect failure %dn", errno);
}
#include <sys/types.h>
#include <sys/socket.h>
int connect(int s, struct sockaddr *name, int namelen)
The bind() call only allows specification of a local address. To specify the remote side of an address connection the connect() call is used. In the call to connect, s is the file descriptor for the socket. name is a pointer to a structure of type sockaddr:
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
As with the bind() system call, 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. A return value of 0 indicates success, while a value of -1 indicates failure with errno describing the error.
A sample code fragment:
struct sockaddr name;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/sock");
if (connect(s, &name, strlen
(name.sa_data) +
sizeof(name.sa_family)) < 0) {
printf("connect failure %dn", errno);
}
Download Socket Programming Interview Questions And Answers
PDF
Previous Question | Next Question |
What this function bind() does? | What this function sendto() does? |