DSIK_C/EasySockets.h

59 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;
}
int CreateServer(const int socket, const int port){
char myhostname[1024];
gethostname(myhostname, 1023);
struct hostent * heLocalHost = malloc(sizeof(struct hostent *));
heLocalHost = gethostbyname(myhostname);
struct sockaddr_in* endpoint = malloc(sizeof(struct sockaddr_in *));
endpoint->sin_family = AF_INET;
endpoint->sin_port = htons(port);
endpoint->sin_addr = *(struct in_addr*) heLocalHost->h_addr;
int retval = bind(socket,
(struct sockaddr*)endpoint,
sizeof(struct sockaddr));
listen(socket, 10);
return 1;
}
int AcceptClient(const int socket, struct sockaddr_in* incoming){
socklen_t sin_size;
return accept(socket,
(struct sockaddr*) &incoming,
&sin_size);
}
#endif //PROJEKTDSIK_EASYSOCKETS_H