关闭

linux下UDP的socket编程

101人阅读 评论(0) 收藏 举报

自己实现了一下,主要是使用了sendto函数和recvfrom函数;

另外recvfrom和recv最主要的区别是可以得到发送端的地址。

下次接着准备实现一下ftp:

发送端:

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

#define PORT 6789
#define Buflen 100
#define Maxiter 20

int main()
{
	struct sockaddr_in send_addr;
	int sockfd, i;
	char content[Buflen], server_ip[Buflen];
	ssize_t send_size;	

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0){
		printf("socket create error\n");
		return -1;
	}

	send_addr.sin_port = htons(PORT);
	send_addr.sin_family = AF_INET;
	send_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	printf("please input dest ip:\n");
	read(0, server_ip, Buflen);
	send_addr.sin_addr.s_addr = inet_addr(server_ip);
	
	for(i = 0; i < Maxiter; i ++){
		printf("please input the send message(not more than 100bytes):\n");
		read(0, content, Buflen);
		send_size = sendto(sockfd, content, Buflen, 0, (struct sockaddr *)&send_addr, sizeof(struct sockaddr));
		if(send_size < 0){
			printf("error! %d iters\n", i);
			return -1;
		} 
	}
	send_size = sendto(sockfd, "stop", 5, 0, (struct sockaddr *)&send_addr,sizeof(struct sockaddr));
	if(send_size < 0){
		printf("error!\n");
		return -1;
	}	
	close(sockfd);
	return 0;
}



接收端:

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <stdlib.h>

#define PORT 6789
#define Buflen 100

int main()
{
	struct sockaddr_in send_addr, recv_addr;
	int sockfd, bind_err;
	ssize_t recv_size;
	char content[Buflen];

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0){
		printf("socket create error!\n");
		return -1;
	}
	
	recv_addr.sin_port = htons(PORT);
	recv_addr.sin_family = AF_INET;
	recv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind_err = bind(sockfd, (struct sockaddr *)&recv_addr, sizeof(struct sockaddr));
	if(bind_err < 0){
		printf("bind error!\n");
		return;
	}

	while(1){
		memset(&send_addr, 0, sizeof(send_addr));
		socklen_t buflen = sizeof(struct sockaddr);
		recv_size = recvfrom(sockfd, content, Buflen, 0, (struct sockaddr *)&send_addr, &buflen);
		if(recv_size < 0){
			printf("recvfrom error!\n");
			return -1;
		}
		if(strncmp(content, "stop", 4) == 0) break;
		printf("recv : %s\n", content);
	}
	close(sockfd);
	return 0;

}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18127次
    • 积分:1116
    • 等级:
    • 排名:千里之外
    • 原创:97篇
    • 转载:11篇
    • 译文:0篇
    • 评论:0条