当前位置: 技术问答>linux和unix
自己写的ping程序为什么没有数据返回
来源: 互联网 发布时间:2016-12-05
本文导语: #include #include #include #include #include #include #include #include #include #include #include #include #include typedef struct sockaddr SA; void err_sys(const char *errmsg); void send_echo_req(int sockfd, struct sockaddr_in *dstaddr); uint16_t in_cksum(uint16_t *addr, int ...
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef
struct sockaddr SA;
void err_sys(const char *errmsg);
void send_echo_req(int sockfd, struct sockaddr_in *dstaddr);
uint16_t in_cksum(uint16_t *addr, int len);
void recv_echo_reply(int sockfd);
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in dstaddr;
if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1)
err_sys("socket");
bzero(&dstaddr, sizeof(dstaddr));
dstaddr.sin_family = AF_INET;
//dstaddr.sin_port = htons(0);
if (inet_pton(AF_INET, argv[1], &dstaddr.sin_addr) icmp_type = ICMP_ECHO;
icmp->icmp_code = 0;
icmp->icmp_id = getpid();
icmp->icmp_seq = 1;
icmp->icmp_cksum = in_cksum((uint16_t *) icmp, sizeof(struct icmp));
if (sendto(sockfd, buf, len, 0, (SA *)dstaddr, dstlen) == -1)
err_sys("sendto");
}
void recv_echo_reply(int sockfd)
{
char buf[100];
ssize_t n;
struct ip *ip;
struct icmp *icmp;
while (1) {
alarm(5); /* set timeout */
if ((n = read(sockfd, buf, sizeof(buf))) == -1)
err_sys("read");
ip = (struct ip *)buf;
if (ip->ip_p != IPPROTO_ICMP) {
fprintf(stderr, "protocol error.rn");
exit(1);
}
icmp = (struct icmp *)(buf + sizeof(struct ip));
if (icmp->icmp_type == ICMP_ECHOREPLY) {
if (icmp->icmp_id != getpid()) {
fprintf(stderr, "not this process.rn");
exit(1);
} else {
printf("destination host is alive.rn");
break;
}
}
}
}
uint16_t in_cksum(uint16_t *addr, int len)
{
int nleft = len;
uint32_t sum = 0;
uint16_t *w = addr;
uint16_t 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);
}
void err_sys(const char *errmsg)
{
perror(errmsg);
exit(1);
}
ping局域网内的主机,用tcpdump监听,发送ICMP后没有返回数据包,谁知道是不是哪里存在问题
|
楼主用wireshark 在 ping的对端上抓包看看 icmp包有到达主机没?
|
单步调试吧
|
先在本机抓包,看是否有你设定的icmp包出去。如果有,再去对方主机看收到没有。
|
用wireshark抓包分析.
|
写网络通信程序,要找问题,要学会抓网络通信包。。