方式一:
1 int GetNetStat( ) 2 { 3 char buffer[BUFSIZ]; 4 FILE *read_fp; 5 int chars_read; 6 int ret; 7 try 8 { 9 memset( buffer, 0, BUFSIZ ); 10 read_fp = popen("ifconfig eth0 | grep RUNNING", "r"); 11 if ( read_fp != NULL ) 12 { 13 chars_read = fread(buffer, sizeof(char), BUFSIZ-1, read_fp); 14 if (chars_read > 0) 15 { 16 ret = 1; 17 } 18 else 19 { 20 ret = -1; 21 } 22 pclose(read_fp); 23 } 24 else 25 { 26 ret = -1; 27 } 28 } 29 catch 30 { 31 ret = -1; 32 } 33 34 return ret; 35 }
方式二:
1 #define NET_PORT 53 2 #define NET_IP "8.8.8.8" //谷歌DNS 3 4 //获取联网状态 5 int check_net(void) 6 { 7 int fd; 8 int in_len=0; 9 struct sockaddr_in servaddr; 10 //char buf[128]; 11 12 in_len = sizeof(struct sockaddr_in); 13 fd = socket(AF_INET,SOCK_STREAM,0); 14 if(fd < 0) 15 { 16 perror("socket"); 17 return -1; 18 } 19 20 /*设置默认服务器的信息*/ 21 servaddr.sin_family = AF_INET; 22 servaddr.sin_port = htons(NET_PORT); 23 servaddr.sin_addr.s_addr = inet_addr(NET_IP); 24 memset(servaddr.sin_zero,0,sizeof(servaddr.sin_zero)); 25 26 /*connect 函数*/ 27 if(connect(fd,(struct sockaddr* )&servaddr,in_len) < 0 ) 28 { 29 30 printf("not connect to internet! "); 31 close(fd); 32 return 0; //没有联网成功 33 } 34 else 35 { 36 printf("=====connect ok!===== "); 37 close(fd); 38 return 1; 39 } 40 }