Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
4
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/wait.h>

int socketFd, socketFdAccept;
struct sockaddr_in mojAddr, odKogoAddr;
char mojeIp[20] = "95.49.132.180";
char mojeIp2[20] = "127.0.0.1";
char wysylkoweIp[20] = "95.49.132.180";
char wysylkoweIp2[20] = "127.0.0.1";

int main(){
	socklen_t _size;
	char bufor[50];
	int numbytes;
	//int ilePolaczen = 3;

	socketFd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(socketFd == -1){
		puts("nie mozna stworzyc gniazda");
		perror("socket: ");
		return -1;
	}	
	
	mojAddr.sin_family = AF_INET;
	mojAddr.sin_port = htons(33601);//wlasny port
	//mojAddr.sin_port = 0;		//automatyczny wybor wolnego	
	//mojAddr.sin_addr.s_addr = htonl(INADDR_ANY);	//sam wybiera nasz adres ip
	mojAddr.sin_addr.s_addr = inet_addr(mojeIp2);	//wlasne wpisanie;

	if ( (bind(socketFd, (struct sockaddr*)&mojAddr, sizeof(struct sockaddr))) == -1){
        	printf("Nie mozna skonfigurowac gniazda\n");
        	close(socketFd);
        	perror("bind: ");        	
     	}

	if(listen(socketFd, SOMAXCONN) == -1) {
	        printf("Nie mozna nasluchiwac\n");
        	close(socketFd);
		perror("listen: ");        	
     	}
	printf("Oczekuje na polaczenie...\n");

	
	
	while(1){	//main accept() loop
		_size = sizeof(struct sockaddr_in);
     		socketFdAccept = accept (socketFd, (struct sockaddr*)&odKogoAddr, &_size);
     		if(socketFdAccept == -1){
        		printf ("Nieudana proba polaczenia!\n");
        		close(socketFd);
      			close(socketFdAccept);
        		perror("accept: ");
			continue;
		}
		printf("server: got connection from %s\n", inet_ntoa(odKogoAddr.sin_addr));
		//ilePolaczen -= 1;
		//if(ilePolaczen == 0) break;

		if (!fork()) { // this is the child process
			close(socketFd); // child doesn’t need the listener

			while(1){
			  	numbytes = recv(socketFdAccept, bufor, 49, 0);
				if (bufor[0] == 'q') break;
				printf("%s\n", bufor);
			}

			close(socketFdAccept);
			exit(0);
		}
		close(socketFdAccept); // parent doesn’t need this
	}
		
	//wait(NULL);
	return 0;
}