tomchesley
Technical User
I am writing a modified udp server, and i almost have it working the way I want, I am only missing the ability to take a string like "8367" and have 2 bytes 32 175 returned
the string is the port # I obtained from the udp server if that helps.
Here is what I have at the moment
the string is the port # I obtained from the udp server if that helps.
Here is what I have at the moment
Code:
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#define DEFAULT_PORT 1235
int main(int count, char *strings[])
{ int sd;
int fport;
int i;
int port=DEFAULT_PORT;
struct sockaddr_in addr;
char buffer[1024];
char sbuffer[1024];
char o1[5], o2[5], o3[5], o4[5]; //set string rep of each octet
int io1, io2, io3, io4; //set int value for each octet
if ( count != 2 )
printf("usage: %s <port>\n...Using default port (%d).\n", strings[0], port);
else
port = atoi(strings[1]);
sd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
perror("bind");
while (1)
{ int bytes, addr_len=sizeof(addr);
for (i = 0; i < 12; i++)
{
sbuffer[i] = 0;
}
bytes = recvfrom(sd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &addr_len);
printf("msg from %s:%d (%d bytes)\n", inet_ntoa(addr.sin_addr),
ntohs(addr.sin_port), bytes);
sscanf(inet_ntoa(addr.sin_addr), "%4[^.].%4[^.].%4[^.].%4[^.]", o1, o2, o3, o4);
fport = ntohs(addr.sin_port);
//int of each octet
io1 = atoi(o1);
io2 = atoi(o2);
io3 = atoi(o3);
io4 = atoi(o4);
printf("From IP:%s %s %s %s: %d\n", o1, o2, o3, o4, fport);
//this is what we received in hex
printf("Received:\n");
printf("%2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x\n",
buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5],
buffer[6], buffer[7], buffer[8], buffer[9], buffer[10], buffer[11]);
//set send buffer to stuff I want
for (i = 4; i < 12; i++)
{
sbuffer[i-4]=buffer[i];
}
//this is the ip
sbuffer[8] = io1;
sbuffer[9] = io2;
sbuffer[10] = io3;
sbuffer[11] = io4;
//port ???
sbuffer[12] = fport;
sbuffer[13] = fport;
printf("Sending:\n");
printf("%2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x %2x\n",
sbuffer[0], sbuffer[1], sbuffer[2], sbuffer[3], sbuffer[4], sbuffer[5],
sbuffer[6], sbuffer[7], sbuffer[8], sbuffer[9], sbuffer[10], sbuffer[11],
sbuffer[12], sbuffer[13]);
sendto(sd, sbuffer, bytes, 0, (struct sockaddr*)&addr, sizeof(addr));
}
close(sd);
}