【发布时间】:2013-02-02 14:29:09
【问题描述】:
亲爱的:
我使用基于python的套接字客户端来发送字符串数据(即日志数据)。
另一方面,我使用 libpcap 在服务器端嗅探字符串数据。
但是我第二次向服务器端发送字符串数据时,客户端出现错误。
如下错误:
Traceback (most recent call last):
File "./udp_client_not_sendback.py", line 21, in <module>
s.sendall(data) #Send UDP data
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
以下是我在客户端和服务器端的代码:
客户端(Python)
import socket, sys
host = sys.argv[1] #Server IP Address
textport = sys.argv[2] #Server Binding Port
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #socket
try:
port = int(textport)
except ValueError:
port = socket.getservbyname(textport, 'udp')
s.connect((host, port)) #connect
while(1):
print "Enter data to transmit:"
data = sys.stdin.readline().strip() #UDP data
s.sendall(data) #Send UDP data
服务器端(C libpcap)
pcap_handler_func(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
{
char timebuf[64];
char addrstr[64];
struct ether_header *ethhdr = (struct ether_header *)bytes;
struct iphdr *ipv4h;
struct ip6_hdr *ipv6h;
memset(timebuf, 0, sizeof(timebuf));
if (ctime_r(&h->ts.tv_sec, timebuf) == NULL) {
return;
}
timebuf[strlen(timebuf) - 1] = '\0';
printf("%s, caplen:%d, len:%d, ", timebuf, h->caplen, h->len);
ipv4h = (struct iphdr *)(bytes + sizeof(struct ether_header));
inet_ntop(AF_INET, &ipv4h->saddr, addrstr, sizeof(addrstr));
printf("src[%s]\n", addrstr);
return;
}
int main()
{
pcap_t *p;
char errbuf[PCAP_ERRBUF_SIZE];
char cmdstr[] = "udp";
struct bpf_program bpfprog;
p = pcap_open_live("eth1", 65536, 1, 10, errbuf);
//Filter
if (pcap_setfilter(p, &bpfprog) < 0) {
fprintf(stderr, "%s\n", pcap_geterr(p));
return 1;
}
//Packet action
if (pcap_loop(p, -1, pcap_handler_func, NULL) < 0) {
fprintf(stderr, "%s\n", pcap_geterr(p));
pcap_close(p);
return 1;
}
pcap_close(p);
return 0;
}
我认为问题是我没有在服务器端绑定套接字,我只是使用 pcap 来捕获字符串数据。
所以第二次在客户端发生了套接字错误。
谁能给我一些建议来解决这个问题?
非常感谢您的帮助。
【问题讨论】:
-
每次运行客户端时,它都会重新连接到服务器。您的服务器尚未准备好进行多个连接(我认为)。
-
我假设 python 部分中的无限打印循环是复制粘贴错误,而不是真的存在?
-
请记住,必须有一个实际的服务器在服务器端运行——我认为
libpcap不会捕获任何进入 NIC 的数据,即使它没有传递到开放端口。 (除非使用混杂模式或原始套接字,或者这两者是相关的。)如果您的服务器(您没有包括在内)被编码为只接受一个连接然后退出,这将解释这种行为。 -
亲爱的 amaurea:是的,这是复制粘贴错误。
-
亲爱的millimoose:但我认为libpacp 具有混杂模式的能力,因为它是由AF_PACKET 实现的。而且我第一次确实捕获了字符串数据,但是第二次捕获了套接字错误。不想在服务端使用socket绑定怎么办?
标签: python linux sockets networking pcap