60 lines
1.7 KiB
C
60 lines
1.7 KiB
C
//
|
|
// Created by s444440 on 10/30/19.
|
|
//
|
|
|
|
#ifndef PROJEKTDSIK_EASYSOCKETS_H
|
|
#define PROJEKTDSIK_EASYSOCKETS_H
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <netinet/in.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <arpa/inet.h>
|
|
#include <netdb.h>
|
|
int CreateSocket(){
|
|
return socket(PF_INET, SOCK_STREAM, 0);
|
|
}
|
|
int Connect(const int socket, const char* ip, const int port){
|
|
struct sockaddr_in adr;
|
|
struct hostent *he;
|
|
he = gethostbyname(ip);
|
|
if (he == NULL) {
|
|
printf("Nieznany host: %s\n",ip);
|
|
return 0;
|
|
}
|
|
adr.sin_family = AF_INET;
|
|
adr.sin_port = htons(port);
|
|
adr.sin_addr = *(struct in_addr*) he->h_addr;
|
|
int addrlen = sizeof(struct sockaddr_in);
|
|
int connectionStatus = connect(socket, (struct sockaddr*)&adr, addrlen);
|
|
if (connectionStatus<0) return connectionStatus;
|
|
return socket;
|
|
}
|
|
struct sockaddr_in endpoint;
|
|
int CreateServer(const int socket, const int port){
|
|
char myhostname[1024];
|
|
gethostname(myhostname, 1024);
|
|
struct hostent * heLocalHost = malloc(sizeof(struct hostent *));
|
|
heLocalHost = gethostbyname(myhostname);
|
|
endpoint.sin_family = AF_INET;
|
|
endpoint.sin_port = htons(port);
|
|
endpoint.sin_addr.s_addr = INADDR_ANY;
|
|
int retval = bind(socket,
|
|
(struct sockaddr*)&endpoint,
|
|
sizeof(struct sockaddr));
|
|
int listen_val = listen(socket, 10);
|
|
return retval;
|
|
}
|
|
int AcceptClient(const int socket, struct sockaddr_in* incoming){
|
|
socklen_t sin_size;
|
|
printf("Waiting to accept...");
|
|
return accept(socket,
|
|
(struct sockaddr*) &incoming,
|
|
&sin_size);
|
|
|
|
}
|
|
|
|
#endif //PROJEKTDSIK_EASYSOCKETS_H
|