当前位置: 技术问答>linux和unix
socket 服务端如何获取IP地址?
来源: 互联网 发布时间:2016-12-03
本文导语: 请问如何获取本机(服务端)的IP ? local_sock_fd = socket(AF_INET,SOCK_STREAM,0); if(local_sock_fd == -1){ perror("ERROR socket()"); return -1; } /*initialize socket addr*/ local_sock_addr...
请问如何获取本机(服务端)的IP ?
local_sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(local_sock_fd == -1){
perror("ERROR socket()");
return -1;
}
/*initialize socket addr*/
local_sock_addr.sin_family = AF_INET;
local_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
local_sock_addr.sin_port = htons(LISTENING_PORT);
int opt = 1;
setsockopt(local_sock_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if( bind(local_sock_fd,(struct sockaddr*)(&local_sock_addr),sizeof(struct sockaddr)) == -1){
perror("ERROR bind()");
return -1;
}
|
getsockname()
|
getaddrinfo 试试
|
是在bind()之后调用的getsockname()?
local_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
试试去掉其中的htonl
local_sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
试试去掉其中的htonl