socket用法linux,linux socket编程,要用到哪些函数,和用法介绍?_Linux_天涯问答_天涯社区...

b10740ea333b5c4d57bdf77eb84a96a4.png

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;

}

◆◆

评论读取中....

请登录后再发表评论!

◆◆

修改失败,请稍后尝试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值