C语言socket判断网络是否联通(支持域名/附源码)


有时候需要用代码判断当前网络是否联通


#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include    <net/if.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>

//#define NET_PORT 53
//#define NET_IP "8.8.8.8" //谷歌DNS
#define NET_PORT 80
#define NET_IP "www.baidu.com" //百度80端口


 

//获取联网状态
int check_net(void)
{
    int fd;
    int in_len=0;
    struct sockaddr_in servaddr;
    struct hostent *host;
    unsigned int inaddr=0l;
    struct in_addr *ipaddr;
    in_len = sizeof(struct sockaddr_in);
    fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd < 0)
    {
        perror("socket");
        return -1;
    }

    /*设置默认服务器的信息*/
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(NET_PORT);
    //servaddr.sin_addr.s_addr = inet_addr(NET_IP);
    memset(servaddr.sin_zero,0,sizeof(servaddr.sin_zero));

    /*判断是主机名还是ip地址*/
    if( inaddr=inet_addr(NET_IP)==INADDR_NONE)
    {
        if((host=gethostbyname(NET_IP) )==NULL) /*是主机名*/
        {
            perror("gethostbyname error");
            return (-1);
        }
		#ifdef DEBUG
        printf("0IP Address : %s\n",inet_ntoa(*((struct in_addr *)host->h_addr)));
        printf("1IP Address : %s\n",inet_ntoa(*((struct in_addr *)host->h_addr_list[1])));
        printf("h_name : %s\n",host->h_name);
        printf("h_aliases : %s\n",host->h_aliases);
        printf("h_addrtype,h_length : %d,%d,AF_INET=%d\n",host->h_addrtype,host->h_length,AF_INET);
		#endif
		//方法1:
        ipaddr = (struct in_addr *)host->h_addr;
		servaddr.sin_addr.s_addr = (ipaddr->s_addr);
		//方法2:这个算是多此一举了!多了一句无用功
//      inaddr = inet_addr(inet_ntoa(*ipaddr));
//		servaddr.sin_addr.s_addr = inaddr;
	}
    else    /*是ip地址*/
    {
        servaddr.sin_addr.s_addr = inaddr;
    }
    /*connect 函数*/
    if(connect(fd,(struct sockaddr* )&servaddr,in_len) < 0 )
    {
        printf("not connect to internet!\n ");
        close(fd);
        return 0; //没有联网成功
    }
    else
    {
        printf("=====connect ok!=====\n");
        close(fd);
        return 1;
    }
}
		


上述函数可能有待于优化,因为如果短时间内连续执行可能会出现停滞的情况,打印不出来connet ok!不过1s调用一次这个函数来检测应该是可以的!

欢迎网友为我指正里面的不足之处!


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值