通过socket得到远端的IP和连接端口
Windows
TCP:
通过socket得到远端的IP和连接端口
SOCKET acceptSock;
acceptSock = accept(listenSock, NULL, NULL);
SOCKADDR_IN sockAddr;
int iLen=sizeof(sockAddr);
getpeername(acceptSock ,(struct sockaddr *)&sockAddr,&iLen);//得到远程IP地址和端口号
char *strAddr = inet_ntoa(sockAddr.sin_addr);//IP
int uIPPort = sockAddr.sin_port; //端口号
///
获取域名对应的IP地址
经过上面的讨论,如果我们想要连接到远程的服务器,我们需要知道对方的IP地址,系统函数gethostbyname便能够实现这个目的。它能够获取域名对应的IP地址并且返回一个hostent类型的结果。其中包含了IP地址信息,他的头文件为netdb.h。
struct hostent { char *h_name; // 主机名 char **h_aliases; // 别名列表 int h_addrtype; // 地址类型int h_length; // 地址的长度 char **h_addr_list; // 地址列表 }其中的h_addr_list便是存放IP地址的信息。
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<sys/socket.h> #include<arpa/inet.h> #include<sys/types.h> #include<netdb.h>int main() {char *hostName = "www.baidu.com";char ip[100];struct hostent *host;struct in_addr **addr_list;int i;if (NULL == (host = gethostbyname(hostName))) {perror("get host by name error");exit(1);}addr_list = (struct in_addr **)host->h_addr_list;for (i = 0; addr_list[i] != NULL; i++) {// inet_ntoa()将long类型的IP地址转化为圆点的字符串形式,作用与inet_addr()相反strcpy(ip, inet_ntoa(*addr_list[i]));}printf("%s resolved to: %s", hostName, ip);return 0; }gethostbyname()用来获取域名对应的IP地址。可以参加gethostbyname()来查看更过的用法。
从socket连接中获取对方IP
由前面能够知道accept()返回的是结构体sockaddr_in,由此很容易得知对方的IP和端口信息。
char *client_ip = inet_ntoa(client.sin_addr); int client_port = ntohs(client.sin_port);
linux
2013-09-30 11:26:13 #include <sys/socket.h> #include <arpa/inet.h>.........struct sockaddr_in sa; int len;.........len = sizeof(sa); if(!getpeername(sockconn, (struct sockaddr *)&sa, &len)) {memset(sql,0,1024);snprintf(sql,1024,"client login. ip: %s, port:%d",inet_ntoa(sa.sin_addr),ntohs(sa.sin_port));snprintf(machine_ip,17,"%s",inet_ntoa(sa.sin_addr));mylog(sql); }
新人创作打卡挑战赛发博客就能抽奖!定制产品红包拿不停!
总结
以上是生活随笔为你收集整理的通过socket得到远端的IP和连接端口的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Docker安装(安装docker)
- 下一篇: 浅谈LSTM