Loading...
Select Version
&pagelevel(3)&pagelevel
The following client program code demonstrates address conversion.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char **argv)
{
struct sockaddr_in server;
struct servent *sp;
struct hostent *hp;
int s;
sp = getservbyname("telnet", "tcp");
if (sp == NULL) {
fprintf(stderr, "telnet/tcp: unknown service\n");
exit(1);
}
hp = gethostbyname(argv[1]);
if (hp == NULL) {
fprintf(stderr, "%s: unknown host\n", argv[1]);
exit(2);
}
memset((char *)&server, 0, sizeof server);
memcpy((char *)&server.sin_addr, hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = sp->s_port;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
perror("socket");
exit(3);
}
/* Connect does the bind for us */
if (connect(s, (struct sockaddr *)&server, sizeof server) < 0) {
perror("connect");
exit(5);
}
exit(0);
}
The example program is only valid for the communications domain AF_INET.
It is also valid for the AF_INET6 domain if you make the following changes:
server is of the type struct sockaddr_in6
struct sockaddr_in6 is supplied with a value from the getaddrinfo or getipnodebyname socket functions (not from gethostbyname as for AF_INET)
You find a more detailed description in "Socket addressing" and "Creating a socket".