在C语言中检测网络是否中断,可以通过尝试建立网络连接来判断。以下是一个简单的示例,使用`socket`函数尝试连接到一个已知的网络服务(如`www.google.com`的HTTP服务端口80),如果连接成功,则认为网络是正常的;如果连接失败,则可能是因为网络中断。
```c
include
include
include
include
include
include
include
int check_network_connection(const char hostname, int port) {
int sockfd;
struct sockaddr_in servaddr;
struct hostent he;
// 获取主机信息
if ((he = gethostbyname(hostname)) == NULL) {
fprintf(stderr, "gethostbyname() failed: %sn", hstrerror(h_errno));
return 0;