4、获得地址信息
/* 来源: http://www.jfox.info/c/a/ic/18071a.html */
#include
#include /* for strncpy */
#include
#include
#include
#include
#include
int
main()
{
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return 0;
}
5、获得地址信息的错误处理 #include
/* 来源: http://www.jfox.info/c/a/ic/18071a.html */
#include
#include
#include
int
main()
{
char *hostname = "localhost";
struct addrinfo hints, *res;
struct in_addr addr;
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
printf("error %d\n", err);
return 1;
}
addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
printf("ip address : %s\n", inet_ntoa(addr));
freeaddrinfo(res);
return 0;
}
6、创建socket地址
/* 来源: http://www.jfox.info/c/a/ic/18071a.html */
#include
#include
#include
#include
int
main()
{
char *hostname = "localhost";
char *service = "80";
struct addrinfo hints, *res;
int err;
int sock;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
if ((err = getaddrinfo(hostname, service, &hints, &res)) != 0) {
printf("error %d : %s\n", err, gai_strerror(err));
return 1;
}
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock
perror("socket");
return 1;
}
if (connect(sock, res->ai_addr, res->ai_addrlen) != 0) {
perror("connect");
return 1;
}
freeaddrinfo(res);
return 0;
}
◆◆
评论读取中....
请登录后再发表评论!
◆◆
修改失败,请稍后尝试