I am very new to socket programming, I want to simulate a client-server transaction. So for my client sent packet, I declare a sock = socket(AF_INET, SOCK_STREAM, 0), a SOCKADDR_IN sin, I bind them through bind(sock, (SOCKADDR*) &sin, sizeof(sin)), then, after declaring a classic struct ip header, and hydrating a allocating some memory to struct iphdr * ip, I finally send the packet via ip
sent_packet = sendto(sock, packet, sizeof(struct iphdr) + sizeof(struct tcphdr),
0, (struct sockaddr *) sin, sizeof(struct sockaddr));//sent_packet is an int, I use also a TCP header struct, packet is the pointer that stores the ip and tcp data
This seems to work. But now, I want to trace the sent packet, so I use a server side file to declare again a sock, I declare a SOCKADDR_IN client_sin I accept the connection of the client via accept(sock, (SOCKADDR*)&client_sin, &recsize);, but it seems that my packet is not received ? I use for that recv(sock, buffer, 32, 0) != SOCKET_ERROR to catch the packets, (of course I launched the server program before the client one). Am going completely wrong ?
Edit on the client side (to shorten, I didn't mention the included libraries, the `struct` `iphdr`, `tcphdr`, the `in_chksum function`, as well I didn't hydrate the tcp header, for now I just want to test)
#define PORT 23
int sendmeifyoucan(SOCKET sock, SOCKADDR_IN * sin , int size ){
struct iphdr * ip = (struct iphdr *)malloc(sizeof(struct iphdr *));
struct tcphdr * tcp;
char * packet;
int psize=0, status = 1;
printf("%d I am lost in the web ",status);
packet = malloc(sizeof(struct iphdr)+ sizeof(struct tcphdr));
memset(packet, 0, sizeof(struct iphdr) + sizeof(struct tcphdr));
sin->sin_addr.s_addr = inet_addr("127.0.0.1");
ip->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + psize);
ip->ihl = 5;
ip->version = 4;
ip->ttl = 255;
ip->tos = 0;
ip->frag_off = 0;
ip->protocol = IPPROTO_ICMP;
ip->saddr = sin->sin_addr.s_addr;
ip->daddr = sin->sin_addr.s_addr;
ip->check = in_chksum((u_short *)ip, sizeof(struct iphdr));
status = sendto(sock, packet, sizeof(struct iphdr) + sizeof(struct tcphdr),
0, (struct sockaddr *) sin, sizeof(struct sockaddr));
free(packet);
return 0;
}
int main(void)
{
int erreur = 0;
SOCKADDR_IN sin;
SOCKET sock;
SOCKADDR_IN csin;
SOCKET csock;
int sock_err;
if(!erreur)
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock != INVALID_SOCKET)
{
printf("La socket %d est maintenant ouverte en mode TCP/IP\n", sock);
int size = 0;
/* Configuration */
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
/* Listage du port */
sendmeifyoucan(sock, &sin,size);
printf("Fermeture de la socket client\n");
closesocket(csock);
printf("Fermeture de la socket serveur\n");
closesocket(sock);
printf("Fermeture du serveur terminée\n");
}
else
perror("socket");
}
return EXIT_SUCCESS;
}
Edit on the server side
#define PORT 23
int main(void)
{
int erreur = 0;
SOCKET sock;
SOCKADDR_IN sin;
socklen_t recsize = sizeof(sin);
SOCKADDR_IN csin;
char buffer[32] = "";
int sock_err;
if(!erreur)
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock != INVALID_SOCKET)
{
printf("La socket %d est maintenant ouverte en mode TCP/IP\n", sock);
/* Configuration */
csin.sin_addr.s_addr = inet_addr("127.0.0.1");
csin.sin_family = AF_INET;
csin.sin_port = htons(PORT);
sock_err = bind(sock, (SOCKADDR*) &csin, sizeof(csin));
if(sock_err != SOCKET_ERROR)
{
sock_err = listen(sock, 5);
printf("Listage du port %d...\n", PORT);
}
if(sock_err != SOCKET_ERROR)
{
/* Attente pendant laquelle le client se connecte */
printf("Patientez pendant que le client se connecte sur le port %d...\n", PORT);
sock = accept(sock, (SOCKADDR*)&sin, &recsize);
}
if(recv(sock, buffer, 32, 0) != SOCKET_ERROR)
{
printf("Recu : %s\n", buffer);
}
else
{
printf("Impossible de se connecter\n");
}
closesocket(sock);
}
else
perror("socket");
}
return EXIT_SUCCESS;
}
You can't use sendto with a SOCK_STREAM socket. Use connect and either send or write instead.
Also, you usually don't use struct iphdr and struct tcphdr in normal socket programming, those are only used with raw ip packets (which sockets aren't).
Related
I'm trying to send a multicast message via a socket, then receive responses from devices on the network that respond.
The message sends successfully, and I can see the responses targeting the source IP address on wireshark, but attempting to call recvfrom just results in timeouts.
I have tried many combinations of socket options, bindings, but I've been unable to get past a timeout on recvfrom.
My current code (sending and receiving):
// Ethernet/IP Encapsulation Header
struct __attribute__((__packed__)) EnipEncapHeader
{
uint16_t command;
uint16_t length;
uint32_t session_handle;
uint32_t status;
uint64_t ctx_64;
uint32_t options;
};
int main() {
// initialize winsock
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
// create a udp socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("ERROR opening socket");
return 1;
}
// set the broadcast flag
int broadcastEnable = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&broadcastEnable, sizeof(broadcastEnable));
// Construct the message
struct EnipEncapHeader header;
header.command = 0x63;
header.length = 0x0000;
header.session_handle = 0x00000000;
header.status = 0x0000;
header.ctx_64 = (uint64_t)0;
header.options = 0x0000;
// send to 255.255.255.255 on port 44818
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("255.255.255.255");
servaddr.sin_port = htons(44818);
// send the packet
int rc = sendto(sockfd, (const char*)&header, sizeof(header), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
if (rc < 0) {
printf("ERROR sending packet, %d, %d", rc, WSAGetLastError());
return 1;
}
// clear the broadcast flag
broadcastEnable = 0;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&broadcastEnable, sizeof(broadcastEnable));
// set the timeout to 5 seconds
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// bind the socket to any address
struct sockaddr_in myaddr;
memset(&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(0);
bind(sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr));
// recieve from any address on the socket
struct sockaddr_in from;
int fromlen = sizeof(from);
char buf[1024];
rc = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
if (rc < 0) {
printf("ERROR recieving packet, %d, %d", rc, WSAGetLastError());
return 1;
}
else {
printf("Received %d bytes from %s:%d", rc, inet_ntoa(from.sin_addr), ntohs(from.sin_port));
}
return 0;
}
This code results in the following:
ERROR recieving packet, -1, 10060
Winsock Error 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
I'm writing a simple network application and I need to craft a UDP packet and send it to a specific host.
int main(void){
// Message to be sent.
char message[] = "This is something";
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if(sockfd < 0){
perror("Error creating socket");
exit(1);
}
struct sockaddr_in this, other;
this.sin_family = AF_INET;
other.sin_family = AF_INET;
this.sin_port = htons(8080);
other.sin_port = htons(8000);
this.sin_addr.s_addr = INADDR_ANY;
other.sin_addr.s_addr = inet_addr("10.11.4.99");
if(bind(sockfd, (struct sockaddr *)&this, sizeof(this)) < 0){
printf("Bind failed\n");
exit(1);
}
char packet[64] = {0};
struct udphdr *udph = (struct udphdr *) packet;
strcpy(packet + sizeof(struct udphdr), message);
udph->uh_sport = htons(8080);
udph->uh_dport = htons(8000);
udph->uh_ulen = htons(sizeof(struct udphdr) + sizeof(message));
udph->uh_sum = 0;
if(sendto(sockfd, packet, udph->uh_ulen, 0, (struct sockaddr *) &other, sizeof(other)) < 0)
perror("Error");
else
printf("Packet sent successfully\n");
close(sockfd);
return 0;
}
Everything is working fine till the call to sendto(). The sendto() is giving "Bad address". can anyone point me where I'm going wrong? Is there any problem with binding a port to a raw socket?
The code transform the length of the messag (udph->uh_len) to network byte order (htons). This is not needed, as the parameter type of size_t. Only port number (in sockaddr structures) need the htons conversion.
udph->uh_ulen = sizeof(struct udphdr) + sizeof(message);
Current code produce large number (>8000) in uh_ulen, causing the send to fail.
I am trying to make a packet router that receives a packet, reads its destination, and sends it on its way. It receives packets just fine, the problem is that when I attempt to do a sendto() I always get the error
sendto() failed: No such device or address
I am grabbing the destination MAC address from the ethernet header of the received packet, loading it into a struct sockaddr_ll and passing that to sendto() but it isn't working.
Also when I ping one host to another the output of my print statements has the source ip as 40.41.42.43 and the destination ip as 44.45.46.47, and neither of those devices exist. Am I reading the ethernet and IP headers correctly? Or maybe the socket is getting messed up somehow?
Anyway here is the code.
int main(int argc, char *argv[])
{
int sock1, sock2, sock3;
int status = 0;
fd_set readfds;
int buffer[256];
int socknum = 0;
// Create 3 sockets
if ((sock1 = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0){
perror("socket() failed");
exit(1);
}
if ((sock2 = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0){
perror("socket() failed");
exit(1);
}
if ((sock3 = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0){
perror("socket() failed");
exit(1);
}
// Bind sockets to interfaces
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "r0-eth1");
if (setsockopt(sock1, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
perror("setsockopt() inf config failed");
exit(1);
}
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "r0-eth2");
if (setsockopt(sock2, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
perror("setsockopt() inf config failed");
exit(1);
}
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "r0-eth3");
if (setsockopt(sock3, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
perror("setsockopt() inf config failed");
exit(1);
}
printf("All sockets bound to interfaces.\n");
while(1)
{
//Setup select
FD_ZERO(&readfds);
FD_SET(sock1, &readfds);
FD_SET(sock2, &readfds);
FD_SET(sock3, &readfds);
printf("Sockets set to read.\n");
struct timeval tv = {2, 0};
printf("Starting select.\n");
status = select( sock3 + 1, &readfds , NULL , NULL , &tv );
printf("status = %d\n", status);
struct sockaddr_in sockAddr;
socklen_t sockLen = sizeof(sockAddr);
memset(&sockAddr, 0, sockLen);
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
int bufLen = 0;
// Check select
if (status > 0) {
printf("status = %d, preparing to read.\n", status);
// Read IP datagram (d)
if (FD_ISSET(sock1, &readfds)) {
printf("Socket 1 ready to receive.\n");
printf("Attempting to receive packet.\n");
bufLen = recvfrom(sock1, buffer, 65535, 0, (struct sockaddr *) &sockAddr, (socklen_t *)&sockLen);
printf("Received packet.\n");
socknum = 1;
}
else if (FD_ISSET(sock2, &readfds)) {
printf("Socket 2 ready to receive.\n");
printf("Attempting to receive packet.\n");
bufLen = recvfrom(sock2, buffer, 65535, 0, (struct sockaddr *) &sockAddr, (socklen_t *)&sockLen);
printf("Received packet.\n");
socknum = 2;
}
else if (FD_ISSET(sock3, &readfds)) {
printf("Socket 3 ready to receive.\n");
printf("Attempting to receive packet.\n");
bufLen = recvfrom(sock3, buffer, 65535, 0, (struct sockaddr *) &sockAddr, (socklen_t *)&sockLen);
printf("Received packet.\n");
socknum = 3;
}
printf("Testing Packet.\n");
struct ethhdr *eth = (struct ethhdr *)(buffer);
printf("\nEthernet Header\n");
printf("\t|-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n",eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_source[3],eth->h_source[4],eth->h_source[5]);
printf("\t|-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n",eth->h_dest[0],eth->h_dest[1],eth->h_dest[2],eth->h_dest[3],eth->h_dest[4],eth->h_dest[5]);
printf("\t|-Protocol : %d\n",eth->h_proto);
// Inspect IP (e)
unsigned short iphdrlen;
struct sockaddr_in source;
struct sockaddr_in dest;
struct iphdr *ip = (struct iphdr*)(buffer + sizeof(struct ethhdr));
memset(&source, 0, sizeof(source));
source.sin_addr.s_addr = ip->saddr;
memset(&dest, 0, sizeof(dest));
dest.sin_addr.s_addr = ip->daddr;
printf("\t|-Version : %d\n",(unsigned int)ip->version);
printf("\t|-Internet Header Length : %d DWORDS or %d Bytes\n",(unsigned int)ip->ihl,((unsigned int)(ip->ihl))*4);
printf("\t|-Type Of Service : %d\n",(unsigned int)ip->tos);
printf("\t|-Total Length : %d Bytes\n",ntohs(ip->tot_len));
printf("\t|-Identification : %d\n",ntohs(ip->id));
printf("\t|-Time To Live : %d\n",(unsigned int)ip->ttl);
printf("\t|-Protocol : %d\n",(unsigned int)ip->protocol);
printf("\t|-Header Checksum : %d\n",ntohs(ip->check));
printf("\t|-Source IP : %s\n", inet_ntoa(source.sin_addr));
printf("\t|-Destination IP : %s\n",inet_ntoa(dest.sin_addr));
printf("index=%d\n",ifreq_i.ifr_ifindex);
// Pull the address from the ethernet header.
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = AF_PACKET;
addr.sll_ifindex = ifr.ifr_ifindex;
addr.sll_halen = ETHER_ADDR_LEN;
addr.sll_protocol = htons(0x0800);
addr.sll_addr[0] = eth->h_dest[0];
addr.sll_addr[1] = eth->h_dest[1];
addr.sll_addr[2] = eth->h_dest[2];
addr.sll_addr[3] = eth->h_dest[3];
addr.sll_addr[4] = eth->h_dest[4];
addr.sll_addr[5] = eth->h_dest[5];
if(sendto(sock1, buffer, bufLen, 0, (struct sockaddr *) &addr, sizeof(addr)) < bufLen){
perror("sendto() failed");
exit(1);
}
}
Any help is appreciated.
I immediately found the answer, but I'm gonna leave this up just in case somebody else has a similar problem. At the bottom part when I am setting up the struct sockaddr_ll addr;. This line:
addr.sll_ifindex = ifr.ifr_ifindex;
should be this instead:
addr.sll_ifindex = ifreq_i.ifr_ifindex;
The socket and the index of the socket were different so sendto() couldn't find a device that fit those parameters.
I wrote a simple UDP broadcast sample. When I write the IP address to the struct sockaddr_in with inet_addr("192.168.152.128"), I cannot receive the message from another UDP broadcast program with the broadcast 192.168.152.255. But when I write htonl(INADDR_ANY), it can receive the message. Why could that be?
This the code:
#include"myhead.h"
char rbuf[50];
char wbuf[50];
int main()
{
int udp, size, len, opt = 1;
struct sockaddr_in laddr;
struct sockaddr_in raddr;
laddr.sin_family = AF_INET;
laddr.sin_port = htons(8888);
laddr.sin_addr.s_addr = htonl(INADDR_ANY);
//when i write inet_addr("192.168.152.128")
//it cannot receive the message.
size = sizeof(struct sockaddr_in);
udp = socket(AF_INET, SOCK_DGRAM, 0);
setsockopt(udp, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
bind(udp, (struct sockaddr*)&laddr, size);
len = sizeof(struct sockaddr);
while (1)
{
recvfrom(udp, rbuf, 50, 0, (struct sockaddr*)&raddr, &len);
printf("%s\n", rbuf);
bzero(rbuf, 50);
}
}
I am emulating a client-server socket transaction. Suppose, the client sent some ip packet with
status = send(sock, packet, sizeof(struct iphdr) + sizeof(struct tcphdr),
0);
where sock is the socket, packet points to an ip packet (with ip header struct iphdr and tcp header struct tcphdr)
Now, on the server side, I want to use some function that retrieves the data in packet and displays it. The connection between client and server is correctly set up but when trying to use the recv function, I don't get any data. Is recv the right function
So on the client side I have
packet = malloc(sizeof(struct iphdr)+ sizeof(struct tcphdr));
and I use
send(sock, packet, sizeof(struct iphdr) + sizeof(struct tcphdr),
0);
on the server side, I declared some char packet[32]; and I used this
recv(sock, packet, 32, 0);
Edit 2 - here's the code
On the client side
Edit on the client side (to shorten, I didn't mention the included libraries, the struct iphdr, tcphdr, the in_chksum function, as well I didn't hydrate the tcp header, for now I just want to test)
struct tcphdr tcp_hdr;
struct ip ip_hdr;
#define PORT 23
int sendmeifyoucan(SOCKET sock, SOCKADDR_IN * sin , int size ){
struct ip * ip = (struct ip *)malloc(sizeof(struct ip));
struct tcphdr * tcp;
char * packet;
int sock_err;
int psize=0, status = 1;
packet = malloc(sizeof(struct ip)+ sizeof(struct tcphdr));
memset(packet, 0, sizeof(struct ip) + sizeof(struct tcphdr));
ip->ip_len = htons(sizeof(struct ip) + sizeof(struct tcphdr) + psize);
ip->ip_hl = 5;
ip->ip_v = 4;
ip->ip_ttl = 255;
ip->ip_tos = 0;
ip->ip_off = 0;
ip->ip_p = IPPROTO_ICMP;
ip->ip_src.s_addr = inet_addr("127.0.0.1");
ip->ip_dst.s_addr = inet_addr("127.0.0.1");
ip->ip_sum = in_chksum((u_short *)ip, sizeof(struct ip));
status = send(sock, packet, sizeof(struct iphdr) + sizeof(struct tcphdr),
0);
free(packet);
return 0;
}
int main(void)
{
int erreur = 0;
SOCKADDR_IN sin;
SOCKET sock;
SOCKADDR_IN csin;
SOCKET csock;
int sock_err;
if(!erreur)
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock != INVALID_SOCKET)
{
printf("La socket %d est maintenant ouverte en mode TCP/IP\n", sock);
int size = 0;
/* Configuration */
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
if(connect(sock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR)
{
printf("Connection à %s sur le port %d\n", inet_ntoa(sin.sin_addr), htons(sin.sin_port));
sendmeifyoucan(sock, &sin,size);
/* Si l'on reçoit des informations : on les affiche à l'écran */
}
}
printf("Fermeture de la socket client\n");
closesocket(csock);
printf("Fermeture de la socket serveur\n");
closesocket(sock);
printf("Fermeture du serveur terminée\n");
}
else
perror("socket");
}
return EXIT_SUCCESS;
}
On the server side
#define PORT 23
int main(void)
{
int erreur = 0;
SOCKET sock;
SOCKADDR_IN sin;
socklen_t recsize = sizeof(sin);
SOCKADDR_IN csin;
char buffer[32] = "";
int sock_err;
if(!erreur)
{
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock != INVALID_SOCKET)
{
printf("La socket %d est maintenant ouverte en mode TCP/IP\n", sock);
/* Configuration */
csin.sin_addr.s_addr = inet_addr("127.0.0.1");
csin.sin_family = AF_INET;
csin.sin_port = htons(PORT);
sock_err = bind(sock, (SOCKADDR*) &csin, sizeof(csin));
if(sock_err != SOCKET_ERROR)
{
sock_err = listen(sock, 5);
printf("Listage du port %d...\n", PORT);
}
if(sock_err != SOCKET_ERROR)
{
/* Attente pendant laquelle le client se connecte */
printf("Patientez pendant que le client se connecte sur le port %d...\n", PORT);
sock = accept(sock, (SOCKADDR*)&sin, &recsize);
}
if(recv(sock, buffer, 32, 0) != SOCKET_ERROR)
{
printf("Recu : %s\n", buffer);
}
else
{
printf("Impossible de se connecter\n");
}
closesocket(sock);
}
else
perror("socket");
}
return EXIT_SUCCESS;
}
Edit 3 - the headers
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#include <stdio.h>
#include <stdlib.h>
#define PORT 23
Okay now I see your problems.
On client side:
First issue (big):
You are not CONNECTING at all.
where is your connect() call on the client side?
If you want to use SOCK_STREAM you need a connect(2) call
In the code snippet:
if(connect(sock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR) {
printf("Connection à %s sur le port %d\n", inet_ntoa(sin.sin_addr), htons(sin.sin_port));
/* Si l'on reçoit des informations : on les affiche à l'écran */
}
your sendmeifyoucan() is OUTSIDE the if block { } ;
2nd issue
struct iphdr * ip = (struct iphdr *)malloc(sizeof(struct iphdr *));
should be
struct iphdr * ip = (struct iphdr *)malloc(sizeof(struct iphdr));
Otherwise you are in a stack overflow issue.
Third issue (not so big)
you are allocating char *packet but you are not copying anything on to it it's just memset to 0;
Debug accordingly and try again :)