使用C 实现服务器端 获取客户端经过所有网络节点IP
时间: 2023-12-14 21:35:54 浏览: 36
要获取客户端经过所有网络节点的IP,可以在服务器端使用getpeername函数获取客户端的IP和端口号,然后通过traceroute命令获取客户端经过的所有网络节点的IP。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
void traceroute(char *ip_addr);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <ip_address>\n", argv[0]);
exit(1);
}
traceroute(argv[1]);
return 0;
}
void traceroute(char *ip_addr) {
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
perror("socket");
exit(1);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
inet_pton(AF_INET, ip_addr, &addr.sin_addr);
int ttl = 1;
setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
while (1) {
printf("%d ", ttl);
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));
char buf[1024];
memset(buf, 0, sizeof(buf));
struct sockaddr_in raddr;
socklen_t rlen = sizeof(raddr);
if (recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&raddr, &rlen) < 0) {
printf("*\n");
} else {
printf("%s\n", inet_ntoa(raddr.sin_addr));
}
if (raddr.sin_addr.s_addr == addr.sin_addr.s_addr) {
break;
}
ttl++;
setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
}
close(sockfd);
}
```
首先创建一个原始套接字,然后设置套接字选项IPPROTO_IP和IP_TTL,初始TTL值为1。在while循环中,先打印当前TTL值,然后设置接收超时时间为1秒,调用recvfrom函数接收ICMP报文,如果超时,则打印星号;否则打印发来报文的IP地址。如果接收到的报文来自目标IP地址,则跳出循环。每次循环结束后,TTL值加1,重新设置套接字选项IPPROTO_IP和IP_TTL。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)