window

#include <stdio.h>
#include <WinSock2.h>

#define PORT	7230
#define IP		"127.0.0.01"
#define MAXLINE	256

struct Msg {
	char data[MAXLINE];
	int length;
	int msgNum;
};

int main(int argc, char **argv) {
	WSADATA wsaData;
	SOCKET sockfd;
	struct sockaddr_in addr, recvAddr;
	int addrlen;
	int currentMsgNum = 0;
	struct Msg msg;

	if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
		return 1;
	}

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
		return -1;
	}

	memset((void *)&addr, 0x00, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.S_un.S_addr = inet_addr(IP);
	addr.sin_port = htons(PORT);

	while(1) {
		memset(msg.data, 0x00, MAXLINE);
		printf(">> ");
		scanf("%s", msg.data);
		msg.length = htonl(strlen(msg.data));
		msg.msgNum = htonl(currentMsgNum++);

		addrlen = sizeof(addr);
		sendto(sockfd, (char *)&msg, sizeof(msg), 0, 
			(struct sockaddr *)&addr, addrlen);

		memset(msg.data, 0x00, MAXLINE);
		recvfrom(sockfd, (char *)&msg, sizeof(msg), 0,
			(struct sockaddr *)&addr, &addrlen);
		printf("SERVER >> %s\n", msg.data);
	}

	closesocket(sockfd);
	WSACleanup();
	return 0;
}


unix

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>

#define PORT 7230
#define MAXLEN 256

struct Msg {
	char data[MAXLEN];
	int length;
	int msgNum;
};

int main(int argc, char **argv) {
	int sockfd;
	socklen_t addrlen;
	struct Msg msg;
	struct sockaddr_in addr, cliaddr;
	int currentNum = 0;

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		return 1;
	}

	memset((void *)&addr, 0x00, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(PORT);

	addrlen = sizeof(addr);
	if(bind(sockfd, (struct sockaddr *)&addr, addrlen) == -1) {
		return -1;
	}

	printf("running...\n");
	while(1) {
		addrlen = sizeof(cliaddr);
		recvfrom(sockfd, (char *)&msg, sizeof(msg), 0,
				(struct sockaddr *)&cliaddr, &addrlen);
		printf("client >> %s\n", msg.data);

		memset((void *)&msg, 0x00, sizeof(msg));
		printf(">> ");
		scanf("%s", msg.data);
		msg.length = htonl(strlen(msg.data));
		msg.msgNum = htonl(currentNum++);

		printf("%s %d %d \n", msg.data, msg.length, msg.msgNum);
		sendto(sockfd, (void *)&msg, sizeof(msg), 0,
				(struct sockaddr *)&cliaddr, addrlen);

	}
	return 1;
}


+ Recent posts