Linux下UDP Socket编程实例

server.c

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

int main(int argc, char **argv) {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        perror("socket error.");
        return -1;
    }

    struct sockaddr_in s_addr;
	memset(&s_addr, 0, sizeof(struct sockaddr_in));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(49152);
	s_addr.sin_addr.s_addr = INADDR_ANY;

	if (bind(fd, (struct sockaddr *)&s_addr, sizeof(s_addr)) < 0) {
		perror("bind error.");
		return -1;
	}

    char buff[10];
    struct sockaddr_in c_addr;
	socklen_t addr_len = sizeof(c_addr);
    int len = recvfrom(fd, buff, sizeof(buff) - 1, 0, (struct sockaddr *) &c_addr, &addr_len);
    if (len < 0) {
        perror("recvfrom error.");
        return -1;
    }
    buff[len] = '\0';

    printf("recive come from %s:%d message:%s\n\r",
        inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buff);
	
	return 0;
}

client.c

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

int main(int argc, char *argv[]) {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        perror("socket error.");
        return -1;
    }

    struct sockaddr_in s_addr;
    memset(&s_addr, 0, sizeof(struct sockaddr_in));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(49152);
    s_addr.sin_addr.s_addr = inet_addr("192.168.3.35");

	if (sendto(fd, "hello", 5, 0, (struct sockaddr *)&s_addr, sizeof(s_addr)) <= 0) {
        perror("sendto error.");
		return -1;
	}

	return 0;
}

你可能感兴趣的:(Linux操作系统)