Cラーニング-LinuxでのTcpサーバ
1795 ワード
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT_NUM 50001
#define MAX_DATA_BUFSIZE 6000
#define ERROR -1
#define OK 0
unsigned char buf[MAX_DATA_BUFSIZE] = {0};
/* Function declaration */
int main()
{
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
int sockAddrSize;
int accept_fd;
int sock_fd;
fd_set fdset;
int bytes_received = 0;
int seq = 0;
int pkt_len = 0;
sockAddrSize = sizeof(struct sockaddr_in);
bzero((char*) &serverAddr, sockAddrSize);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT_NUM);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == ERROR)
{
printf("Error: socket()!
");
return ERROR;
}
if (bind(sock_fd, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) == ERROR)
{
printf("Error: bind()!
");
close(sock_fd);
return ERROR;
}
while (1)
{
if ((bytes_received = recvfrom(sock_fd, buf, MAX_DATA_BUFSIZE, 0, (struct sockaddr *) &clientAddr, &sockAddrSize)) > 0)
{
/* Print the contents of the received msg, the first 4 bytes is seq num */
seq = (buf[0]<<24) + (buf[1]<<16) + (buf[2]<<8) + buf[3];
printf("Received %4d bytes Data. seq=%d
", bytes_received, seq);
}
}
close(sock_fd);
return OK;
}