All pastes #4010318 Raw Edit

Something

public unlisted text v1 · immutable
#4010318 ·published 2018-04-03 09:24 UTC
rendered paste body
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

char bigData[30000];
int done = 0;

int initServerSocket(int portNum)
{
    int socketId[1], ret, option = 1;
    struct sockaddr_in addressInfo;

    *socketId = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (*socketId < 0)
    {
        return -1;
    }
	
    addressInfo.sin_family = AF_INET;
    addressInfo.sin_addr.s_addr = htonl(INADDR_ANY);
    addressInfo.sin_port = htons(portNum);
	
    ret = bind(*socketId, (struct sockaddr *) &addressInfo, sizeof(addressInfo));
    if (ret < 0)
    {
        return -1;
    }
	
    return *socketId;
}

int main()
{
	memset(bigData, 'a', 30000);
	bigData[29999] = '\0';
	
	signed int socket = initServerSocket(12345);
	
	if(socket == -1)
	{
		return -1;
	}
	
	const int flags = fcntl(socket, F_GETFL, 0);
	fcntl(socket, F_SETFL, flags ^ O_NONBLOCK);
	
    int ret = listen(socket, 5);
    if (ret < 0)
	{
		return -1;
	}
	
	while(!done) 
	{			
		struct sockaddr_in addrInfoFromClient;
		int retSharedSocketIdWithClient;
		socklen_t sizeAddrInfo = sizeof(addrInfoFromClient);
		memset(&addrInfoFromClient, 0, sizeof(addrInfoFromClient));
			
		char buf[128];
			
		retSharedSocketIdWithClient = accept4(socket, (struct sockaddr *) &addrInfoFromClient, &sizeAddrInfo, SOCK_NONBLOCK);
		if (retSharedSocketIdWithClient >= 0)
		{
			int i = recv(retSharedSocketIdWithClient, buf, sizeof(buf), 0);
			printf("received: %d bytes\n", i);
			printf("received: %s\n", buf);
			
			
			i = send(retSharedSocketIdWithClient, bigData, strlen(bigData), 0);
			if(i < strlen(bigData))
			{
				i += send(retSharedSocketIdWithClient, bigData + i, strlen(bigData) - i, 0);
			}
			
			shutdown(retSharedSocketIdWithClient, SHUT_WR);
			printf("sent %d bytes\n", i);
			done = 1;
		}
	}
	return 0;
}