1. 程式人生 > >Linux網絡編程(一):一個簡單的socket程序

Linux網絡編程(一):一個簡單的socket程序

服務 htonl 網絡 pre fin efi from ret span

服務器:

/*
 *tcp_server.c
 */

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define SER_PORT 8000
#define MAX_LINE 1024

int main(int argc, char **argv)
{
    int listenfd, connfd;
    struct sockaddr_in servaddr, cliaddr;
    socklen_t cliaddr_len;
    
char buff[MAX_LINE]; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SER_PORT); bind(listenfd, (struct sockaddr *)&servaddr, sizeof
(servaddr)); listen(listenfd, 20); while(1) { cliaddr_len = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len); printf("receive from %s at port %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)), ntohs(cliaddr.sin_port)); close(connfd); }
return 0; }

客戶端:

/*
 *tcp_client.c
 */

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>

#define SER_PORT 8000
#define MAX_LINE 1024

int main(int argc, char **argv)
{
    int sockfd;
    struct sockaddr_in servaddr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
    servaddr.sin_port = htons(SER_PORT);
    
    if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        printf("connect error:%s\n", strerror(errno));
    }
    
    return 0;
}

參考:

《UNIX網絡編程 - 卷1:套接字聯網API》

Linux網絡編程(一):一個簡單的socket程序