How to determine the socket connection status in Linux using getsockopt?

In Linux, the getsockopt function can be used to check the status of a socket connection. This function is used to retrieve the value of socket options. Specifically, the SO_ERROR option can be used to obtain the error code of a socket connection in order to determine its status.

Here is an example:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int sockfd;
    int error;
    socklen_t len = sizeof(error);

    // 创建socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }

    // 连接到服务器
    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(80);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        perror("connect");
        return 1;
    }

    // 获取socket选项的值
    if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
        perror("getsockopt");
        return 1;
    }

    // 判断socket连接状态
    if (error == 0) {
        printf("Socket connected successfully.\n");
    } else {
        printf("Socket connection failed with error %d.\n", error);
    }

    // 关闭socket
    close(sockfd);

    return 0;
}

In the example above, a socket is first created and connected to the specified server. Then the getsockopt function is used to retrieve the value of the SO_ERROR option, which is stored in the error variable. Finally, the status of the socket connection is determined based on the value of error; if error is 0, the connection is successful, otherwise it is deemed a failure and the error code is printed. Finally, the socket is closed.

It is important to note that the third parameter of the getsockopt function is SO_ERROR, which is an integer used to store the error code of the socket connection. Additionally, you need to include the header files sys/types.h and sys/socket.h.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds