【问题标题】:ICMP socket (win)ICMP 套接字(获胜)
【发布时间】:2016-09-30 02:28:12
【问题描述】:

如果地址向上返回 1,如果地址向下返回 0,我想制作一个程序作为检查网。这是代码:

#include <stdio.h>
#include <winsock2.h>
#include <stdint.h>
#pragma comment(lib, "ws2_32.lib")

static void init(void)
{

    WSADATA wsa;
    int err = WSAStartup(MAKEWORD(2, 2), &wsa);
    if(err < 0)
    {
        puts("WSAStartup failed !");
        exit(EXIT_FAILURE);
    }

}

static void end(void)
{

    WSACleanup();

}

int chknet(char * ip) 
{ 
    struct sockaddr_in name; 
    struct hostent * hent; 
    int sock; 
    int retour = 0; 
init();
/* creat socket  icmp */ 
           if(!(sock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP))) return (-1); 
                     memset(&name,0,sizeof(struct sockaddr_in)); 
                     name.sin_family = AF_INET; 
                     name.sin_addr.s_addr = inet_addr(ip); 
           if(connect(sock,(struct sockaddr *) &name,sizeof(struct sockaddr))==0) retour = 1; 
           else retour = 0; 

end();
return(retour); 
}
// Fonction main *************************** 
int main(int argc, char *argv[])
{
    char *adress="www.stackoverflow.com";
    int a= chknet(adress);
   printf("result %d\n",a);
    system("PAUSE");

}

当我连接到互联网时,它返回 1,但即使我没有连接,它也返回 1,但它应该返回 0。 谢了

【问题讨论】:

    标签: c sockets winsock2 icmp


    【解决方案1】:

    您将字符串"www.stackoverflow.com" 传递给函数inet_addr()。此函数需要一个“IPv4 数字和点表示法”地址,例如 151.101.1.69——因此您需要先进行 DNS 查找,使用类似 gethostbyname() 的地址。

    检查您调用的函数的返回码总是一个好主意...

    【讨论】:

    • 但在这两种情况下我都得到了 1。例如,如果我在 adress="12.2" 中创建,它将返回 1。但是我的网络中没有这样的地址。
    • connect() 可能返回正常,因为 s_addr 中有一些随机值。使用本地网络上某些东西的实际地址怎么样?并检查返回的错误代码的实际值,也许用perror() 打印它们。否则你只是在猜测。
    • 我担心这个(来自我的手册页):The inet_addr() function converts the Internet host address cp from IPv4 numbers-and-dots notation into binary data in network byte order. If the input is invalid, INADDR_NONE (usually -1) is returned. Use of this function is problematic because -1 is a valid address (255.255.255.255). Avoid its use in favor of inet_aton(), inet_pton(3), or getaddrinfo(3), which provide a cleaner way to indicate error return. 你应该检查你得到了你所期望的,或者接受不使用该功能的建议。
    • 我的意思是,出了点问题,但我们不知道是什么。要追踪它,请检查您调用的每个函数的返回码,直到找到问题为止。
    猜你喜欢
    • 2012-01-07
    • 2010-11-10
    • 2012-01-19
    • 2020-02-22
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    相关资源
    最近更新 更多