C语言Linux下的Socket 编程

(1) client端,发数据:

udp_client.c文件


#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<sys/types.h>

#include<sys/socket.h>

#include<netinet/in.h>

#include<arpa/inet.h>

#include<netdb.h>

#include<unistd.h>

#define SIZE 100

int main(int argc, char **argv){

    int         sd;

    struct      sockaddr_in server;

    struct      hostent *hp;

    char        *temp_buf;

    char        *address;

    temp_buf = (char *)malloc(sizeof(char) * SIZE);

    temp_buf[0] = 'a';

    temp_buf[1] = 'b';

    sd = socket(AF_INET, SOCK_DGRAM, 0);

    server.sin_family = AF_INET;

    server.sin_port = htons(12345);

    address = "127.0.0.1";

    inet_pton(AF_INET, address, &server.sin_addr);

    for(;;){

        sendto(sd, temp_buf, strlen(temp_buf), 0, (struct sockaddr *) &server, sizeof(server));

        sleep(2);

    }  

    close(sd);

}

(2) server端,接收数据:
udp_server.c文件
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<unistd.h>
#define SIZE 100
#define MAXLINE 256
int main(int argc, char **argv){
    int         n, sd;
    struct      sockaddr_in server, send_addr;
    char        recv_buf[MAXLINE];
    char        *temp_buf;
    temp_buf = (char *)malloc(sizeof(char) * SIZE);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(12345);
    sd = socket(AF_INET, SOCK_DGRAM, 0);
    bind(sd, (struct sockaddr *)&server, sizeof(server));
    for(;;){
         n = recvfrom(sd, recv_buf, MAXLINE, 0, (struct sockaddr *)&send_addr, (socklen_t *) sizeof(send_addr));
        printf("Received: %s\n", recv_buf);
    }  
        
    close(sd);
    return 0;
}

相关推荐