You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.6 KiB
86 lines
2.6 KiB
/*
|
|
** Copyright (C) 2020 Johannes Kepler University Linz, Institute of Networks and Security
|
|
** Copyright (C) 2020 CDL Digidow <https://www.digidow.eu/>
|
|
**
|
|
** Licensed under the EUPL, Version 1.2 or – as soon they will be approved by
|
|
** the European Commission - subsequent versions of the EUPL (the "Licence").
|
|
** You may not use this work except in compliance with the Licence.
|
|
**
|
|
** You should have received a copy of the European Union Public License along
|
|
** with this program. If not, you may obtain a copy of the Licence at:
|
|
** <https://joinup.ec.europa.eu/software/page/eupl>
|
|
**
|
|
** Unless required by applicable law or agreed to in writing, software
|
|
** distributed under the Licence is distributed on an "AS IS" basis,
|
|
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
** See the Licence for the specific language governing permissions and
|
|
** limitations under the Licence.
|
|
**
|
|
*/
|
|
|
|
#include "client.h"
|
|
|
|
int client_open(char *servip, int16_t port) {
|
|
struct sockaddr_in servaddr;
|
|
size_t servaddr_len = 0;
|
|
int connfd = 0;
|
|
|
|
connfd = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (-1 == connfd) {
|
|
printf("client_listen: failed to create endpoint.\n");
|
|
return -1;
|
|
}
|
|
bzero(&servaddr, sizeof(servaddr));
|
|
|
|
servaddr.sin_family = AF_INET;
|
|
servaddr.sin_addr.s_addr = inet_addr(servip);
|
|
servaddr.sin_port = htons(port);
|
|
servaddr_len = sizeof(servaddr);
|
|
if (0 != connect(connfd, (const struct sockaddr *) &servaddr, servaddr_len)) {
|
|
printf("client_accept: connection to server failed\n");
|
|
close(connfd);
|
|
return -1;
|
|
}
|
|
return connfd;
|
|
}
|
|
|
|
int client_connect(conn_handler handler, char *servip, int16_t port) {
|
|
int connfd = 0;
|
|
char buffer[MAX_BUFSIZE];
|
|
int ret = 0;
|
|
int len = 0;
|
|
|
|
connfd = client_open(servip, port);
|
|
if(0 >= connfd) {
|
|
return -1;
|
|
}
|
|
bzero(buffer, MAX_BUFSIZE);
|
|
for (ret = 0; 0 == ret;) {
|
|
ret = handler(buffer);
|
|
if(0 > ret || 1 == ret)
|
|
break;
|
|
|
|
if (0 >= write(connfd, buffer, strlen(buffer))) {
|
|
printf("client_connect: cannot write to socket\n");
|
|
ret = -1;
|
|
}
|
|
if(2 == ret)
|
|
break;
|
|
|
|
bzero(buffer, MAX_BUFSIZE);
|
|
len = read(connfd, buffer, sizeof(buffer));
|
|
if (0 > len) {
|
|
printf("client_connect: cannot read from socket\n");
|
|
ret = -1;
|
|
} else if (0 == len) {
|
|
printf("client_connect: server closed connection\n");
|
|
ret = 1;
|
|
}
|
|
}
|
|
|
|
if (0 != close(connfd)) {
|
|
printf("client_connect: failed to close server connection properly\n");
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|