socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")
时间: 2024-06-21 09:02:39 浏览: 226
这段代码使用Python中的socket模块创建了一个原始套接字,用于发送ICMP数据包[^1]。其中,AF_INET是指使用IPv4地址族,SOCK_RAW是指使用原始套接字,getprotobyname("icmp")是获取ICMP协议的编号。这种类型的套接字可以让应用程序访问底层通信协议,从而实现原始数据包的发送和接收。
如果想要测试在你的操作系统下是否支持某个socket类型,可以使用C语言中的socket函数。下面是一个例子,它使用socket函数创建一个SOCK_RDM类型的socket,并返回socket描述符。如果创建失败,程序会输出错误信息。在Linux系统下,SOCK_RDM已经废弃,因此程序运行时会输出"Protocol not supported"的错误信息[^2]。
```c
#include <stdio.h>
#include <sys/socket.h>
int main() {
int sock_fd = socket(AF_INET, SOCK_RDM, 0);
if (sock_fd == -1) {
perror("socket: ");
} else {
printf("sock_fd: %d\n", sock_fd);
}
return 0;
}
```
相关问题
用Windows实现代码socket实现ping命令
使用 socket 实现 ping 命令的过程如下:
1. 创建一个 ICMP 套接字。
2. 构造 ICMP 报文。
3. 发送 ICMP 报文并开始计时。
4. 等待接收 ICMP 响应报文。
5. 接收到响应报文后,停止计时并计算往返时间(RTT)。
6. 打印结果。
下面是用 Python 实现 ping 命令的示例代码:
```python
import socket
import struct
import time
def ping(host):
# 创建 ICMP 套接字
icmp = socket.getprotobyname('icmp')
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
# 构造 ICMP 报文
ID = 65535 # 任意一个 16 位数值
seq_num = 1
payload = b'hello, world!'
packet = struct.pack('!BBHHH', 8, 0, 0, ID, seq_num) + payload
# 发送 ICMP 报文并开始计时
start_time = time.time()
sock.sendto(packet, (host, 1))
# 等待接收 ICMP 响应报文
try:
sock.settimeout(5)
data, addr = sock.recvfrom(1024)
except socket.timeout:
print('Request timed out.')
return
# 接收到响应报文后,停止计时并计算往返时间(RTT)
end_time = time.time()
rtt = (end_time - start_time) * 1000
# 打印结果
print('Reply from %s: time=%.2fms' % (addr[0], rtt))
sock.close()
if __name__ == '__main__':
ping('www.baidu.com')
```
运行结果:
```
Reply from 14.215.177.38: time=26.39ms
```
socket实现ping命令的c+代码
以下是一个简单的使用socket实现ping命令的C代码。该代码通过创建一个ICMP数据包并发送给指定的主机,并等待响应来模拟ping命令。
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <sys/time.h>
#define PACKET_SIZE 4096
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 3
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd, datalen = 56;
unsigned short cal_chksum(unsigned short *addr, int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
if (nleft == 1) {
*(unsigned char *)(&answer) = *(unsigned char *)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;
}
int pack(int pack_no)
{
int i, packsize;
struct icmp *icmp;
struct timeval *tval;
icmp = (struct icmp*)sendpacket;
icmp->icmp_type = ICMP_ECHO;
icmp->icmp_code = 0;
icmp->icmp_cksum = 0;
icmp->icmp_seq = pack_no;
icmp->icmp_id = getpid();
packsize = 8 + datalen;
tval = (struct timeval*)icmp->icmp_data;
gettimeofday(tval, NULL);
icmp->icmp_cksum = cal_chksum((unsigned short*)icmp, packsize);
return packsize;
}
int unpack(char *buf, int len)
{
int i, iphdrlen;
struct iphdr *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip = (struct iphdr*)buf;
iphdrlen = ip->ihl << 2;
icmp = (struct icmp*)(buf + iphdrlen);
len -= iphdrlen;
if (len < 8) {
printf("ICMP packets\'s length is less than 8\n");
return -1;
}
if ((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == getpid())) {
tvsend = (struct timeval*)icmp->icmp_data;
gettimeofday(&tvsend, NULL);
rtt = (tvsend->tv_sec - tvsend->tv_sec) * 1000.0 + (tvsend->tv_usec - tvsend->tv_usec) / 1000.0;
printf("%d bytes from %s: icmp_seq=%u ttl=%d time=%.1f ms\n", len, inet_ntoa(*(struct in_addr*)&ip->saddr), icmp->icmp_seq, ip->ttl, rtt);
} else {
return -1;
}
}
void send_packet()
{
int packetsize;
static int pack_no = 0;
pack_no++;
packetsize = pack(pack_no);
if (sendto(sockfd, sendpacket, packetsize, 0, (struct sockaddr*)&dest_addr, sizeof(dest_addr)) < 0) {
printf("sendto error\n");
}
}
void recv_packet()
{
int n, fromlen;
struct timeval tv;
fd_set readfd;
fromlen = sizeof(from);
while (1) {
tv.tv_sec = MAX_WAIT_TIME;
tv.tv_usec = 0;
FD_ZERO(&readfd);
FD_SET(sockfd, &readfd);
n = select(sockfd + 1, &readfd, NULL, NULL, &tv);
if (n == 0) {
printf("timeout\n");
return;
}
if (recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0, (struct sockaddr*)&from, &fromlen) < 0) {
printf("recvfrom error\n");
}
if (unpack(recvpacket, n) == -1) {
printf("unpack error\n");
}
}
}
void ping()
{
int i;
for (i = 0; i < MAX_NO_PACKETS; i++) {
send_packet();
recv_packet();
sleep(1);
}
}
int main(int argc, char *argv[])
{
struct hostent *host;
struct protoent *protocol;
unsigned long inaddr = 0l;
int waittime = MAX_WAIT_TIME * 1000;
int size = 50 * 1024;
if (argc < 2) {
printf("usage:%s hostname/IP address\n", argv[0]);
exit(1);
}
if ((protocol = getprotobyname("icmp")) == NULL) {
printf("getprotobyname error\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0) {
printf("socket error\n");
exit(1);
}
setuid(getuid());
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
bzero(&dest_addr, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
if ((inaddr = inet_addr(argv[1])) == INADDR_NONE) {
if ((host = gethostbyname(argv[1])) == NULL) {
printf("gethostbyname error\n");
exit(1);
}
memcpy((char*)&dest_addr.sin_addr, host->h_addr, host->h_length);
} else {
memcpy((char*)&dest_addr.sin_addr, &inaddr, sizeof(inaddr));
}
printf("PING %s (%s): %d data bytes\n", argv[1], inet_ntoa(dest_addr.sin_addr), datalen);
ping();
return 0;
}
```
阅读全文