添加代码
这是个很常见的问题:在bind函数之前添加如下代码即可。
cppint yes = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); }
查看端口
如果还是不能结果,那么说明是真的冲突了,例如查看当前UDP ipv4使用的端口号,如下所示:如果发现端口已被使用,则kill掉相关进程,或者使用其他的端口号
netstat -a4un //查看UDP端口
netstat -a4tn //查看TCP端口
bash
$ netstat -a4un
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
udp 0 0 0.0.0.0:37745 0.0.0.0:*
udp 0 0 0.0.0.0:5353 0.0.0.0:*
udp 0 0 0.0.0.0:55408 0.0.0.0:*
udp 0 0 0.0.0.0:48385 0.0.0.0:*
udp 0 0 127.0.0.53:53 0.0.0.0:*
udp 0 0 0.0.0.0:69 0.0.0.0:*
udp 0 0 0.0.0.0:111 0.0.0.0:*
udp 0 0 0.0.0.0:620 0.0.0.0:*
udp 0 0 0.0.0.0:631 0.0.0.0:*
udp 0 0 0.0.0.0:59068 0.0.0.0:*
udp 0 0 192.168.0.11:9990 192.168.0.3:37143 ESTABLISHED
udp 0 0 0.0.0.0:42876 0.0.0.0:*
udp 0 0 0.0.0.0:2049 0.0.0.0:*
bash
$ netstat -a4tn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:6013 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:56063 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:2049 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:37699 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:37195 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:48533 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN
tcp 0 0 192.168.0.11:22 192.168.0.5:60730 ESTABLISHED
tcp 0 0 192.168.0.11:2049 192.168.0.3:730 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:57805 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:53147 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:57305 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:54349 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:53241 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:60727 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:57306 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:56891 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:54348 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:56892 ESTABLISHED
tcp 0 0 192.168.0.11:22 192.168.0.5:57405 ESTABLISHE