Proxy DNS not receiving response - c

I am creating proxy dns and I recieved query from dig, send it to server but can´t get answer from dns server. I know my code doesn´t look good but I am working on this for hours and still can´t get what is wrong. My program just stuck before second recvfrom. Can someone help me? (btw my OS for this is FreeBSD and I am testing this with 8.8.8.8 dns server)
This is my code:
int main(int argc, char *argv[] )
{
char buf[BUFSIZE];
char serverbuf[BUFSIZE];
int UDPSocket, clientSocket;
int lenght;
int addr_len;
struct addrinfo *clientInfo;
struct addrinfo hintsClient;
struct sockaddr_in serverSocket, clientAddr, serverAddr;
int serverAddrLen = sizeof(serverAddr);
fd_set set, tcpset;
struct timeval tv; // struktura pro timeout
bool end = false;
int m;
TprogParam param = processParams(argc, argv);
if(param.error)
{
printError(EPARAMS);
return ERROR;
}
if(param.help)
{
printHelp();
return EXIT_SUCCESS;
}
memset(&hintsClient, 0, sizeof(struct addrinfo));
hintsClient.ai_family = AF_INET;
hintsClient.ai_socktype = SOCK_DGRAM;
hintsClient.ai_flags = 0;
hintsClient.ai_protocol = IPPROTO_UDP;
int status;
if(param.ipadress[0] == '\0')
{
if((status = getaddrinfo(INADDR_ANY, NULL, &hintsClient, &clientInfo)) != 0)
{
printf("Spatna adresa pro naslouchani");
printError(1);
return ERROR;
}
}
else
{
if((status = getaddrinfo(param.ipadress, "13066", &hintsClient, &clientInfo)) != 0)
{
printf("Spatna adresa pro naslouchani");
printError(1);
return ERROR;
}
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(param.dnsserver);;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = 53;
// vytvorime socket
if((UDPSocket = socket(clientInfo->ai_family, clientInfo->ai_socktype, clientInfo->ai_protocol)) == -1)
{
printf("Nelze vytvorit udp socket");
printError(1);
return ERROR;
}
if((clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
printf("Nelze vytvorit tcp socket");
printError(1);
return ERROR;
}
// Nastavime socket do neblokovaciho rezimu
if(bind(UDPSocket, clientInfo->ai_addr, clientInfo->ai_addrlen) == -1)
{
if (errno != EINPROGRESS)
{
printf("Nelze navazat spojeni pro naslouchani: %d", errno);
return ERROR;
}
}
printf("Poslal jsem zadost o spojeni. Zatimco se spojeni navazuje mohu delat jine veci.\n");
FD_ZERO(&set);
FD_SET(UDPSocket, &set);
tv.tv_sec = 15;
tv.tv_usec = 0;
addr_len = sizeof(struct sockaddr);
while(1)
{
printf("Prijimam pozadavek k vyrizeni.\n");
if ((lenght = recvfrom(UDPSocket, buf, BUFSIZE - 1, 0, (struct sockaddr *)&clientAddr, &addr_len)) == -1)//recv(UDPSocket, buf, BUFSIZE - 1, 0)) == -1)
{
printf("Nejaka chyba pri prijimani dat");
return ERROR;
}
buf[lenght] = '\0';
printf("Prijata nasledujici data od klienta na predklad dns: %s o delce %d \n", buf, lenght);
if((m = sendto(clientSocket, buf, lenght, 0, (struct sockaddr *)&serverAddr, serverAddrLen)) == -1)
{
printf("Problem s odeslanim dat: %d %s", errno, strerror(errno));
return ERROR;
}
if((m = recvfrom(clientSocket, buf, BUFSIZE - 1, 0, (struct sockaddr *)&serverAddr,&serverAddrLen)) == -1)
{
printf("nejaka chyba");
return ERROR;
}
if((lenght = sendto(UDPSocket, buf, lenght, 0,(struct sockaddr *)&clientAddr, lenght)) == -1)
{
printf("Problem s odeslanim dat: errno %d", errno);
return ERROR;
}
}
}
Edit: New code after some fixes:
#include "dns_stat.h"
TprogParam processParams(int argc, char *argv[]) {
TprogParam parInfo =
{
.error = false,
.help = false,
.ipadress[0] = '\0',
.port = 0,
.dnsserver[0] = '\0',
.type = false,
.source = false,
.destination = false,
};
if(argc == 1)
{
parInfo.help = true;
}
else
{
int c;
const char *short_options = ":l:p:s:";
const struct option long_options[] = {
{ "type", 0, NULL, 't' },
{ "source", 0, NULL, 'z' },
{ "destination", 0, NULL, 'd' },
{ NULL, 0, NULL, 0 }
};
while((c = getopt_long_only(argc, argv, short_options, long_options, NULL)) != -1) {
switch (c) {
case 'l':
strcpy(parInfo.ipadress,optarg);
break;
case 'p':
parInfo.port = atoi(optarg);
break;
case 's':
strcpy(parInfo.dnsserver,optarg);//optarg);
//parInfo.dnsserver = strdup(optarg);
break;
case 't':
parInfo.type = true;
break;
case 'z':
parInfo.source = true;
break;
case 'd':
parInfo.destination = true;
break;
case '?':
parInfo.error = true;
break;
default:
printf("default");
parInfo.error = true;
abort();
}
}
}
return parInfo;
}
void printHelp()
{
printf("Napoveda\n");
}
void printError(int ecode)
{
if(ecode<EOK||ecode>EUNKNOWN){
ecode = EUNKNOWN;
}
fprintf(stderr, "%s", ECODEMSG[ecode]);
}
int main(int argc, char *argv[] )
{
char buf[BUFSIZE];
char serverbuf[BUFSIZE];
int UDPSocket, clientSocket;
int lenght;
int addr_len;
struct addrinfo *clientInfo;
struct addrinfo hintsClient;
struct sockaddr_in serverSocket, clientAddr, serverAddr;
int serverAddrLen = sizeof(serverAddr);
fd_set set, tcpset;
struct timeval tv; // struktura pro timeout
bool end = false;
bool end2 = false;
int m;
TprogParam param = processParams(argc, argv);
if(param.error)
{
printError(EPARAMS);
return ERROR;
}
if(param.help)
{
printHelp();
return EXIT_SUCCESS;
}
//printf("type: %d, source: %d, destination: %d\n", param.type, param.source, param.destination);
memset(&hintsClient, 0, sizeof(struct addrinfo));
hintsClient.ai_family = AF_INET;
hintsClient.ai_socktype = SOCK_DGRAM;
hintsClient.ai_flags = 0;
hintsClient.ai_protocol = IPPROTO_UDP;
int status;
if(param.ipadress[0] == '\0')
{
if((status = getaddrinfo(INADDR_ANY, NULL, &hintsClient, &clientInfo)) != 0)
{
printf("Spatna adresa pro naslouchani");
printError(1);
return ERROR;
}
}
else
{
if((status = getaddrinfo(param.ipadress, "13066", &hintsClient, &clientInfo)) != 0)
{
printf("Spatna adresa pro naslouchani");
printError(1);
return ERROR;
}
}
memset(&serverAddr, 0, sizeof(serverAddr));
;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(param.dnsserver);;
serverAddr.sin_port = htons(53);
// vytvorime socket
if((UDPSocket = socket(clientInfo->ai_family, clientInfo->ai_socktype, clientInfo->ai_protocol)) == -1)
{
printf("Nelze vytvorit udp socket");
printError(1);
return ERROR;
}
if((clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
printf("Nelze vytvorit tcp socket");
printError(1);
return ERROR;
}
// Nastavime socket do neblokovaciho rezimu
if(bind(UDPSocket, clientInfo->ai_addr, clientInfo->ai_addrlen) == -1)
{
if (errno != EINPROGRESS)
{
printf("Nelze navazat spojeni pro naslouchani: %d", errno);
return ERROR;
}
}
printf("Poslal jsem zadost o spojeni. Zatimco se spojeni navazuje mohu delat jine veci.\n");
FD_ZERO(&set);
FD_SET(UDPSocket, &set);
tv.tv_sec = 15;
tv.tv_usec = 0;
addr_len = sizeof(struct sockaddr);
while(1)
{
printf("Prijimam pozadavek k vyrizeni.\n");
if ((lenght = recvfrom(UDPSocket, buf, BUFSIZE - 1, 0, (struct sockaddr *)&clientAddr, &addr_len)) == -1)//recv(UDPSocket, buf, BUFSIZE - 1, 0)) == -1)
{
printf("Nejaka chyba pri prijimani dat");
return ERROR;
}
buf[lenght] = '\0';
printf("Prijata nasledujici data od klienta na predklad dns: %s o delce %d \n", buf, lenght);
if((m = sendto(clientSocket, buf, lenght, 0, (struct sockaddr *)&serverAddr, serverAddrLen)) == -1)
{
printf("Problem s odeslanim dat: %d %s", errno, strerror(errno));
return ERROR;
}
printf("tady");
fflush(stdout);
if((m = recvfrom(clientSocket, buf, BUFSIZE - 1, 0, (struct sockaddr *)&serverAddr,&serverAddrLen)) == -1)
{
printf("nejaka chyba");
return ERROR;
}
printf("Prijata nasledujici data od dns serveru: %s o delce %d \n", buf, lenght);
if((lenght = sendto(UDPSocket, buf, lenght, 0,(struct sockaddr *)&clientAddr, addr_len)) == -1)
{
printf("Problem s odeslanim dat: errno %d %s", errno, strerror(errno));
return ERROR;
}
}
}

At least two issues here:
serverAddr.sin_addr.s_addr = inet_addr(param.dnsserver);; /* line 1 */
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* line 2 */
serverAddr.sin_port = 53; /* line 3 */
Line 2 overwrites server address you just translated on line 1. Just remove line 2.
Line 3 needs to change to htons(53) to convert port number to network byte order.

Related

UDP winsock chat program receives -1 from recvfrom() and sendto()

Currently, we are producing UDP chat programs using MFC and C.
I'm working on both bind because I have to send incoming messages from the server and client.
An error occurs when recvfrom() and sendto(), they return -1.
I don't know what the problem is. I searched it and did what I did, but it's not working.
Why does sendto() and recvfrom() return -1?
I don't know what the problem is.
server Code
static UINT UdpServerFunc(LPVOID pVoid)
{
CServerDlg *dlg = (CServerDlg *)AfxGetApp()->m_pMainWnd;
//------------------------------------------------------
CString slniPath;
slniPath.Format(_T("./NetworkPath.ini"));
TCHAR ServerPort[MAX_PATH];
int ServerPort_Num;
GetPrivateProfileString(_T("ServerInfo"), _T("Port"), _T(""), ServerPort, MAX_PATH, slniPath);
ServerPort_Num = _ttoi(ServerPort);
//------------------------------------------------------
//Startup Winsock
WSADATA wsaData;
int retval = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (retval != 0)
{
AfxMessageBox("WSAStartup() Error\n");
return 0;
}
//SOCKET
dlg->server_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//IPPROTO_UDP or PPROTO_HOPOPTS
if (dlg->server_sock == SOCKET_ERROR)
{
AfxMessageBox("Socket() Error\n");
return 0;
}
ZeroMemory(&dlg->server_addr, sizeof(dlg-> server_addr));
dlg->server_addr.sin_family = AF_INET;
dlg->server_addr.sin_port = htons(ServerPort_Num); //30112
dlg->server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
dlg->client_addr.sin_family = AF_INET;
dlg->client_addr.sin_port = htons(ServerPort_Num);
dlg->client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
retval = bind(dlg->server_sock, (SOCKADDR*)&dlg->server_addr, sizeof(dlg->server_addr));
AfxMessageBox("server start");
if (retval == SOCKET_ERROR) {
AfxMessageBox("bind() ERROR\n");
return -1;
}
//Data Communication
int addrlength;
char buf[BUFFER_SIZE];
int recv_size;
while (1)
{
//recvfrom()
addrlength = sizeof(dlg->client_addr);
recv_size = recvfrom(dlg->server_sock, reinterpret_cast<char*>(buf), BUFFER_SIZE, 0, (SOCKADDR*)&dlg->client_addr, &addrlength);
if (recv_size == SOCKET_ERROR)
{
AfxMessageBox("recvfrom() Error");
break;
}
//Data print
buf[recv_size] = '\0';
CString strMsg;
strMsg = CString(buf, recv_size);
dlg->m_ListChat.AddString(strMsg);
strMsg = "";
}
closesocket(dlg->server_sock);
WSACleanup;
}
Server Sendto Code
void CServerDlg::OnBnClickedButton2()
{
CServerDlg *dlg = (CServerDlg *)AfxGetApp()->m_pMainWnd;
CString strText = _T("");
char Text[BUFFER_SIZE];
dlg->m_edit_chat.GetWindowText(strText);
strcpy(Text, strText);
int send_size = sendto(dlg->server_sock, Text, strlen(Text), 0, (sockaddr*)&dlg->client_addr, sizeof(dlg->client_addr));
if (send_size == SOCKET_ERROR)
{
AfxMessageBox("sendto() Error");
}
else
{
dlg->m_ListChat.AddString(strText);
}
}
Client Code
static UINT ClientUdpThreadFunc(LPVOID pVOID) {
CClientTestDlg *dlg = (CClientTestDlg *)AfxGetApp()->m_pMainWnd;
CString slniPath;
slniPath.Format(_T("./NetworkPath.ini"));
TCHAR ServerPort[MAX_PATH];
int ServerPort_Num;
GetPrivateProfileString(_T("ServerInfo"), _T("Port"), _T(""), ServerPort, MAX_PATH, slniPath);
ServerPort_Num = _ttoi(ServerPort); //30112
TCHAR ServerIp[MAX_PATH];
int ServerIp_Num;
GetPrivateProfileString(_T("ServerInfo"), _T("IP"), _T(""), ServerIp, MAX_PATH, slniPath);
ServerIp_Num = _ttoi(ServerIp); //127.0.0.1
//--------------------------------------------------
//StartUp Winsock
WSADATA wsaData;
int retval = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (retval != 0)
{
AfxMessageBox("WSAStartup() Error\n");
return 0;
}
//socket
dlg->clnt_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (dlg->clnt_sock == SOCKET_ERROR) {
AfxMessageBox(_T("socket() Error"));
return 0;
}
ZeroMemory(&dlg->ServerAddr, sizeof(dlg->ServerAddr));
dlg->ServerAddr.sin_family = AF_INET;
dlg->ServerAddr.sin_port = htons(ServerPort_Num);
dlg->ServerAddr.sin_addr.s_addr = inet_addr(SERVERIP);
/*
dlg->FromServer.sin_family = AF_INET;
dlg->FromServer.sin_port = htons(ServerPort_Num);
dlg->FromServer.sin_addr.s_addr = inet_addr(SERVERIP);
*/
retval = bind(dlg->clnt_sock, (SOCKADDR*)&dlg->ServerAddr, sizeof(dlg->ServerAddr));
if (retval == SOCKET_ERROR) {
AfxMessageBox("bind() ERROR\n");
return -1;
}
//Data Communication
CString strMsg;
int addrlength;
char buf[BUF_SIZE];
int recv_size;
while (1) {
addrlength = sizeof(dlg->FromServer);
recv_size = recvfrom(dlg->clnt_sock, reinterpret_cast<char*>(buf), BUF_SIZE, 0, (sockaddr*)&dlg->FromServer, &addrlength);
if (recv_size == SOCKET_ERROR)
{
AfxMessageBox("recvfrom() ERROR");
break;
}
else
{
//Data print
buf[recv_size] = '\0';
strMsg = CString(buf, recv_size);
dlg->m_listChat.AddString(strMsg);
strMsg = "";
}
}
closesocket(dlg->clnt_sock);
WSACleanup;
}
Client Sendto Code
void CClientTestDlg::OnBnClickedButtonSend()
{
CClientTestDlg *dlg = (CClientTestDlg *)AfxGetApp()->m_pMainWnd;
CString UdpStrText = _T("");
char Text[BUF_SIZE];
m_editChat.GetWindowText(UdpStrText);
strcpy(Text, UdpStrText);
int UdpRtn;
UdpRtn = sendto(dlg->clnt_sock, Text, strlen(Text), 0, (SOCKADDR*)&dlg->ServerAddr, sizeof(dlg->ServerAddr));
if (UdpRtn == SOCKET_ERROR)
{
AfxMessageBox("sendto() ERROR\n %s");
}
closesocket(dlg->clnt_sock);
}

Segfault in client disconnection

I have a simple client-server program implemented in C where a client can send integers to a server and the server replies with their sums. However, there is a troubling Segmentation fault (core dumped) shown on the server side whenever the client disconnects suddenly. The Client:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 5010
int main(int argc, char **argv) {
char buf[BUFSIZ], buf2[BUFSIZ], message[BUFSIZ], serverReply[BUFSIZ];
int SOCKET;
struct sockaddr_in server;
SOCKET = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET < 0) {
perror("Could not create socket");
return -1;
}
printf("Socket created\n");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (connect(SOCKET, (struct sockaddr *) &server, sizeof(struct sockaddr_in)) < 0) {
perror("Could not connect");
return -1;
}
memset(&serverReply, 0, sizeof(serverReply));
printf("Connected to server.\nEnter first number: ");
scanf("%s", buf);
fflush(stdin);
printf("Enter second number: ");
scanf("%s", buf2);
strcat(buf, " ");
strcat(buf, buf2);
strcpy(message, buf);
if (send(SOCKET, message, strlen(message), 0) < 0) {
perror("Failed to send message");
return -1;
}
if (recv(SOCKET, serverReply, sizeof(serverReply), 0) < 0) {
perror("Could not receive message");
return -1;
}
printf("Server: %s", serverReply);
close(SOCKET);
}
The Server:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#define PORT 5010
int main(int argc, char *argv[]) {
char msg[BUFSIZ], reply[BUFSIZ];
struct sockaddr_in server, client;
int SOCKET, ACCEPT, READ, sockSize, num1, num2, option = 1, maxClients = 30,
h, clientSocket[maxClients], maxsd, sd, SELECT;
fd_set readfds;
for (h = 0; h < maxClients; h++) {
clientSocket[h] = 0;
}
SOCKET = socket(AF_INET, SOCK_STREAM, 0);
if (SOCKET == -1) {
perror("Could not create socket");
return -1;
}
if (setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) == -1) {
perror("Could not set OPTNAME");
return -1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
printf("Created socket.\n");
if (bind(SOCKET, (struct sockaddr *) &server, sizeof(server)) < 0) {
perror("Could not bind");
return -1;
}
if (listen(SOCKET, 1) < 0) {
perror("Listen failed");
return -1;
}
printf("Server is listening.\n");
sockSize = sizeof(struct sockaddr_in);
while (1) {
FD_ZERO(&readfds);
FD_SET(SOCKET, &readfds);
maxsd = SOCKET;
for (h = 0; h < maxClients; h++) {
sd = clientSocket[h];
if (sd > 0) { FD_SET(sd, &readfds); }
if (sd > maxsd) { maxsd = sd; }
}
SELECT = select(maxsd + 1, &readfds, NULL, NULL, NULL);
if ((SELECT < 0) && (errno != EINTR)) {
perror("select error");
}
if (FD_ISSET(SOCKET, &readfds)) {
ACCEPT = accept(SOCKET, (struct sockaddr *) &server, (socklen_t *) &sockSize);
if (ACCEPT < 0) {
perror("Could not accept client");
return -1;
}
for (h = 0; h < maxClients; h++) {
if (clientSocket[h] == 0) {
clientSocket[h] = ACCEPT;
break;
}
}
printf("Client has joined the server.\n");
}
for (h = 0; h < maxClients; h++) {
sd = clientSocket[h];
if (FD_ISSET(sd, &readfds)) {
READ = read(sd, msg, sizeof(msg));
if (READ == -1) {
perror("Could not receive message");
return -1;
}
if (READ == 0) {
printf("Client disconnected\n");
fflush(stdout);
clientSocket[h]=0;
}
int e = 0;
char *p = strtok(msg, " ");
char *arr[2];
while (p != NULL) {
arr[e++] = p;
p = strtok(NULL, " ");
}
num1 = atoi(arr[0]);
num2 = atoi(arr[1]);
if ((strcmp(arr[0], "0") != 0 && num1 != 0) && (strcmp(arr[1], "0") != 0 && num2 != 0)) {
printf("Client: %d, %d\n", num1, num2);
sprintf(reply, "%d\n", num1 + num2);
if (write(sd, reply, strlen(reply)) < 0) {
perror("Could not send message");
return -1;
}
memset(&reply, 0, sizeof(reply));
} else {
printf("Conversion error");
strcpy(reply, "Conversion error.");
if (write(sd, reply, strlen(reply)) < 0) {
perror("Could not send message");
return -1;
}
}
}
}
}
}
How can the segfault be solved? How else can the codes be improved?
The segfault comes from the atoi function since NULL is received. Checking for NULL seems to do the trick...

multiple clients stop and wait with C & UDP

I am implementing stop&wait with c and udp socket programming. with one client it works but with more than one client it dosen't work.
server.c
struct sockaddr_in newAddr;
socklen_t addr_size = sizeof(newAddr);
fd_set rset;
int frame_id = 0;
Frame frame_recv;
Frame frame_send;
int socket_desc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socket_desc < 0) {
perror("Socket Creation Failed ");
exit(EXIT_FAILURE);
}
else {
perror("Socket Created ");
}
if (bind(socket_desc, (struct sockaddr *) &server_addr,
sizeof(server_addr)) < 0 ) {
perror("Bind Failed ");
exit(EXIT_FAILURE);
}
else {
perror("Bind Done ");
}
printf("Listening for Messages...\n");
FD_ZERO(&rset);
while (1) {
FD_SET(socket_desc, &rset);
select(socket_desc + 1, &rset, NULL, NULL, NULL);
if (FD_ISSET(socket_desc, &rset)) {
int recv_size = recvfrom(socket_desc, &frame_recv, sizeof(Frame), 0,
(struct sockaddr *) &newAddr, &addr_size);
if (recv_size > 0 && frame_recv.frame_kind == 1 &&
frame_recv.sq_no == frame_id) {
printf("[+]Frame Received: %s\n", frame_recv.packet.data);
frame_send.sq_no = 0;
frame_send.frame_kind = 0;
frame_send.ack = frame_recv.sq_no + 1;
sendto(socket_desc, &frame_send, sizeof(frame_send), 0,
(struct sockaddr*)&newAddr, addr_size);
printf("[+]Ack Send\n");
}
else {
printf("[+]Frame Not Received\n");
break;
}
frame_id ++;
}
}
close(socket_desc);
client.c
char buffer[1024];
socklen_t addr_size;
int frame_id = 0;
Frame frame_send;
Frame frame_recv;
int ack_recv = 1;
int socket_desc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socket_desc < 0) {
perror("Socket Creation Failed ");
exit(EXIT_FAILURE);
}
else {
perror("Socket Created ");
}
while (1) {
if (ack_recv == 1) {
frame_send.sq_no = frame_id;
frame_send.frame_kind = 1;
frame_send.ack = 0;
printf("Enter Data: ");
scanf("%s", buffer);
strcpy(frame_send.packet.data, buffer);
sendto(socket_desc, &frame_send, sizeof(Frame), 0,
(struct sockaddr*)&server_addr, sizeof(server_addr));
printf("[+]Frame Send\n");
}
int addr_size = sizeof(server_addr);
int recv_size = recvfrom(socket_desc, &frame_recv, sizeof(frame_recv), 0 ,(struct sockaddr*)&server_addr, &addr_size);
if (recv_size > 0 && frame_recv.sq_no == 0 && frame_recv.ack == frame_id + 1) {
printf("[+]Ack Received\n");
ack_recv = 1;
}
else {
printf("[-]Ack Not Received\n");
ack_recv = 0;
break;
}
frame_id++;
}
close(socket_desc);
header.h
typedef struct packet {
char data[1024];
} Packet;
typedef struct frame {
int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
} Frame;
I found that frame_recv.sq_no and frame_id have different value when the second client run.
I read questions with same topic, but could not find out the error from my code.

Socket Programming Send / Recv Before Scanf

Im trying to create connection between 2 clients via a server. In this program, client sends a message to the server and server post it to the target client. But there is a little problem between this operation. Transmitter one cannot send another message before it receive some message or receiver one cannot see the received message before send a message. Video should explain better.
You can find scanf function in below of client.c codes
CLIENT
//
// Created by berkin on 18.12.2016.
//
#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> // for inet_addr
#include <string.h>
#include <zconf.h>
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
char message[2000], server_reply[2000];
//Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8888);
//Connect to remote server
if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
perror("Connect failed. Error");
return 1;
}
puts("Connected to server\n");
//keep communicating with server
while (1) {
printf("> ");
scanf("%[^\n]%*c", message);
fflush(stdin);
//Send some data
if (send(sock, message, strlen(message)+1, 0) < 0) {
puts("Send failed");
return 1;
}
if (recv(sock, server_reply, 2000, 0) < 0) {
puts("recv failed");
break;
}
//Receive a reply from the server
printf ("\033[32;1m %s \033[0m\n",server_reply);
}
close(sock);
return 0;
}
SERVER
#include<stdio.h>
#include<string.h> // for strlen
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h> // for inet_addr
#include<unistd.h> // for write
#include<pthread.h> // for threading, link with lpthread
#include "split.h"
#define MAX_CLIENT_NUMBER 100
void *connection_handler(void *);
struct User {
char userName[10];
int clientSocketNo;
};
unsigned int clientNumber = 0;
unsigned int userArrayIndex = 0;
struct User users[MAX_CLIENT_NUMBER];
//FOR GETUSERS COMMAND
void getUsers(int socketNumber) {
char *userString = malloc(100);
if (users[0].userName != NULL) {
strcpy(userString, users[0].userName);
strcat(userString, ",");
} else {
return;
}
for (int i = 1; i < userArrayIndex; ++i) {
strcat(userString, users[i].userName);
strcat(userString, ",");
}
write(socketNumber, userString, strlen(userString) + 1);
}
//AFTER LOGIN COMMAND, ADD TO THE ARRAY
void addUserToArray(char userName[10], int socketNumber) {
printf("Client logged in as %s\n", userName);
strcpy(users[userArrayIndex].userName, userName);
users[userArrayIndex].clientSocketNo = socketNumber;
userArrayIndex++;
}
//LOGIN COMMAND
void loginUser(char userName[10], int socketNumber) {
char *message = "login successful";
write(socketNumber, message, strlen(message) + 1);
addUserToArray(userName, socketNumber);
}
//SEND MESSAGE IF USER FOUND
void sendMessage(struct User user, char *message){
write(user.clientSocketNo,message,strlen(message) + 1);
}
//SEARCH USER FROM ARRAY
struct User searchUser(char searchName[10]){
for (int i = 0; i < userArrayIndex; ++i) {
if(strcmp(users[i].userName,searchName) == 0){
return users[i];
}
}
}
void *connection_handler(void *socket_desc) {
//Get the socket descriptor
char receivedMessage[2000]; //client's message
int readControl;
int parsedItemNumber = 0;
int sock = *((int *) socket_desc);
while ((readControl = recv(sock, receivedMessage, 2000, 0)) > 0) {
char *parsedCommand[50]; //parsedClientMessage
parsedItemNumber = parsing(parsedCommand, receivedMessage, " ");
if (strcmp(parsedCommand[0], "login") == 0) {
loginUser(parsedCommand[1], sock);
}
else if (strcmp(parsedCommand[0], "getusers") == 0) {
getUsers(sock);
}
else if (strcmp(parsedCommand[0], "exit") == 0) {
close(sock);
return 0;
}
else{
if(parsedCommand[0] != NULL){
struct User find = searchUser(parsedCommand[0]);
if(find.userName != NULL){
char *message = malloc(2000);
if(parsedCommand[1] != NULL){
strcpy(message,parsedCommand[1]);
strcat(message," ");
}
for (int i = 2; i < parsedItemNumber; ++i) {
strcat(message,parsedCommand[i]);
strcat(message," ");
}
sendMessage(find,message);
}
else{
perror("Your input was wrong");
}
}
}
}
if (readControl == 0) {
puts("Client disconnected");
clientNumber--;
fflush(stdout);
} else if (readControl == -1) {
perror("recv failed");
}
//Free the socket pointer
free(socket_desc);
return 0;
}
int main(int argc, char *argv[]) {
int socket_desc, new_socket, c, *new_sock;
struct sockaddr_in server, client;
//Create Socket
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc == -1) {
puts("Could not create socket");
return 1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0) {
puts("Binding failed");
return 1;
}
listen(socket_desc, 3);
puts("Server started");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(socket_desc, (struct sockaddr *) &client, (socklen_t *) &c)) &&
clientNumber < MAX_CLIENT_NUMBER) {
pthread_t sniffer_thread[MAX_CLIENT_NUMBER];
new_sock = malloc(1);
*new_sock = new_socket;
if (pthread_create(&sniffer_thread[clientNumber], NULL, connection_handler,
(void *) new_sock) < 0) {
perror("Could not create thread");
return 1;
} else {
clientNumber++;
}
puts("Client connected");
}
if (new_socket < 0) {
perror("accept failed");
return 1;
}
return 0;
}

what are the changes from the linux code to qnx code?

int CreateSocket()
{
//pthread_attr_t attr;
// Socket creation for UDP
acceptSocket = socket(AF_INET,SOCK_DGRAM,0);
if(acceptSocket == -1)
{
printf("Failure: socket creation is failed, failure code\n");
return 1;
}
else
{
printf("Socket started!\n");
}
memset(&addr, 0, sizeof(addr));
addr.sin_family=AF_INET;
addr.sin_port=htons(port);
addr.sin_addr.s_addr=htonl(INADDR_ANY);
rc=bind(acceptSocket,(struct sockaddr*)&addr,sizeof(addr));
fcntl(acceptSocket, O_NONBLOCK);
if(rc== -1)
{
printf("Oh dear, something went wrong with bind()! %s\n", strerror(errno));
return -1;
}
else
{
printf("Socket an port %d \n",port);
}
return acceptSocket;
}
int create_timer (void)
{
timer_t timer_id;
int timerfd = timer_create (CLOCK_REALTIME, 0, &timer_id);
if (timerfd < 0) {
perror ("timerfd_create:");
return -1;
}
return timerfd;
}
int start_timer_msec (int fd, int msec)
{
struct itimerspec timspec;
memset (&timspec, 0, sizeof(timspec));
timspec.it_value.tv_sec = 0;
timspec.it_value.tv_nsec = msec * 1000 * 1000;
if (timer_settime(fd, 0, &timspec, NULL) < 0) {
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
Xcp_Initialize();
int fd_2ms = create_timer();
int fd_10ms = create_timer();
int fd_100ms = create_timer();
int rval = 0;
if ((fd_2ms < 0) || (fd_10ms < 0) || (fd_100ms < 0)) {
exit (1);
}
if ((sock = CreateSocket()) < 0) {
perror ("Create_socket");
// fclose (fp);
exit (1);
}
start_timer_msec (fd_2ms, 2);
start_timer_msec (fd_10ms, 10);
start_timer_msec (fd_100ms, 100);
do
{
socklen_t len;
int max_fd = 0;
fd_set rdfds;
FD_ZERO (&rdfds);
GET_MAX_FD (max_fd, sock);
FD_SET (sock, &rdfds);
GET_MAX_FD (max_fd, fd_2ms);
FD_SET (fd_2ms, &rdfds);
GET_MAX_FD (max_fd, fd_10ms);
FD_SET (fd_10ms, &rdfds);
GET_MAX_FD (max_fd, fd_100ms);
FD_SET (fd_100ms, &rdfds);
rval = select (max_fd, &rdfds, NULL, NULL, NULL);
if (rval < 0) {
if (errno == EINTR)
continue;
} else if (rval > 0) {
/*Process CLI*/
if ((FD_ISSET (sock, &rdfds)))
{
FD_CLR(sock, &rdfds);
len = sizeof(client);
printf("NEW DATA ARRIVED\n");
//non blocking mode : MSG_DONTWAIT
rc=recvfrom(sock, buf, 256, 0, (struct sockaddr*) &client, &len);
//I am calculating the time here
//InterruptTime = GetTimeStamp();
//measurements[17] = InterruptTime;
if(rc==0)
{
printf("Server has no connection..\n");
break;
}
if(rc==-1)
{
if (errno == SIGINT)
continue;
printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
break;
}
ConfigureISR( );
XcpIp_RxCallback( (uint16) rc, (uint8*) buf, (uint16) port );
}
if ((FD_ISSET (fd_2ms, &rdfds))) {
FD_CLR(fd_2ms, &rdfds);
TASK1(Task2ms_Raster);
start_timer_msec (fd_2ms, 2);
}
if ((FD_ISSET (fd_10ms, &rdfds))) {
FD_CLR(fd_10ms, &rdfds);
TASK2(Task10ms_Raster);
start_timer_msec (fd_10ms, 10);
}
if ((FD_ISSET (fd_100ms, &rdfds))) {
FD_CLR(fd_100ms, &rdfds);
TASK3(Task100ms_Raster);
start_timer_msec (fd_100ms, 100);
}
}
} while (1);
close(sock);
//fclose (fp);
return 0;
}
I created a socket to receive data from client via the ip address and port number. I created a timer to call the task for every 2ms, 10ms and 100ms. The above code is working fine for linux. But how to convert the above code for QNX RTOS. What are the changes should I make for QNX rtos. could some one please help me ??
IF I use the same code in qnx then it is crashing at int fd_2ms = create_timer(); !!

Resources