데이터 플러그인 서비스와 클라이언트

3054 단어
이곳에서는 데이터 메시지 플러그인으로 통신하는 것을 연습한다.
listener.c
//  (listener.c): , 

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

#define MYPORT 5000
#define MAXBUFLEN 100

int main(int argc, char *argv[])
{
	int sock_fd;
	struct sockaddr_in my_addr;
	struct sockaddr_in their_addr;
	int addr_len, numbytes;
	char buf[MAXBUFLEN];

	if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perror("socket");
		return 1;
	}
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(MYPORT);
	my_addr.sin_addr.s_addr = INADDR_ANY;	//  IP
	bzero(&(my_addr.sin_zero), 8);			//  

	if(bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1)
	{
		perror("bind");
		return 1;
	}
	addr_len = sizeof(struct sockaddr);
	if((numbytes = recvfrom(sock_fd, buf, MAXBUFLEN, 0, (struct sockaddr*)&their_addr, &addr_len)) == -1)
	{
		perror("recvfrom");
		return 1;
	}
	close(sock_fd);
	printf("got packet from %s
", inet_ntoa(their_addr.sin_addr)); printf("packet is %d bytes long
", numbytes); buf[numbytes] = 0; printf("packet contains [%s]
", buf); return 0; }

talker.c
 
//  (talker.c): 

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

#define MYPORT 5000

int main(int argc, char *argv[])
{
	int sock_fd, numbytes;
	struct sockaddr_in their_addr;
	struct hostent *he;

	if(argc < 3)
	{
		fprintf(stderr, "Usage: %s <hostname> <message>
", argv[0]); return 1; } if((he = gethostbyname(argv[1])) == NULL) { herror("gethostbyname"); return 1; } if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); return 1; } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(MYPORT); their_addr.sin_addr = *((struct in_addr*)he->h_addr); bzero(&(their_addr.sin_zero), 8); if((numbytes = sendto(sock_fd, argv[2], strlen(argv[2]), 0, (struct sockaddr*)&their_addr, sizeof(struct sockaddr))) == -1) { perror("sendto"); return 1; } close(sock_fd); printf("sent %d bytes to %s
", numbytes, inet_ntoa(their_addr.sin_addr)); return 0; }

좋은 웹페이지 즐겨찾기