2011/06/16

C socket client in Linux - sample code

Sample code

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define LOCAL_IP                        "127.0.0.1"
#define LOCAL_PORT                      5678
#define SVR_IP                          "127.0.0.1"
#define SVR_PORT                        8080
#define BUF_SIZE                        1024
#define MESSAGE                         "hello"

int main (int argc, char **argv) {
    struct sockaddr_in  local_addr, server_addr;
    socklen_t           len;
    int                 sock_fd;
    char                buff[BUF_SIZE];
    int                 recv_len;
    
    len = sizeof(struct sockaddr_in);
    
    /* Set local address (In general, we don't care local address) */
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = inet_addr(LOCAL_IP);
    local_addr.sin_port = htons(LOCAL_PORT);
    
    /* Set server address */
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SVR_IP);
    server_addr.sin_port = htons(SVR_PORT);

    /* Create endpoint */
    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket()");
        return -1;
    } else {
        printf("sock_fd=[%d]\n", sock_fd);
    }

    /* Bind */
    if (bind(sock_fd, (struct sockaddr *)&local_addr, sizeof(local_addr)) == -1) {
        perror("bind()");
        return -1;
    } else {
        printf("bind [%s:%u] success\n",
            inet_ntoa(local_addr.sin_addr), ntohs(local_addr.sin_port));
    }

    /* Connect */
    if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("connect()");
        return -1;
    } else {
        printf("connect to [%s:%u] success\n",
            inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));
    }
    
    /* Send */
    send(sock_fd, MESSAGE, strlen(MESSAGE), 0);

    /* Receive */
    memset(buff, 0, sizeof(buff));
    recv_len = recv(sock_fd, buff, sizeof(buff), 0);
    if (recv_len == -1) {
        perror("recv()");
        return -1;
    } else if (recv_len == 0) {
        printf("Client disconnect\n");
    } else {
        printf("Receive: len=[%d] msg=[%s]\n", recv_len, buff);
    }
    
    return 0;
}



沒有留言:

張貼留言