Why does recvfrom create additional IP header? - c

Why does recvfrom create additional IP header?
I am sending:
-------------
- IP header -
-------------
- Data -
-------------
But when I try to receive data, it looks like there is
-------------
- IP header -
-------------
- IP header -
-------------
- Data -
-------------
Client code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <netinet/ip.h>
#define DEBUG 1
int main(void) {
// Create File descrptor for socket
int socket_fd;
if ((socket_fd = socket(AF_INET, SOCK_RAW, IPPROTO_IPV6)) < 0) {
perror("ERROR Socket");
exit(2);
}
char *srcIP = "127.0.0.1";
char *dstIP = "127.0.0.1";
// Create address structure
struct sockaddr_in daddr;
daddr.sin_family = AF_INET;
daddr.sin_port = 0; // Raw sockets can't use ports
inet_pton(AF_INET, "127.0.0.1", &daddr.sin_addr);
memset(daddr.sin_zero, 0, sizeof(daddr.sin_zero));
// Create a Packet
char packet[50];
memset(packet, 0, sizeof(packet));
// Structure packet
struct iphdr *ip_header = (struct iphdr *) packet;
// Data to be appended at the end of the ip header
char *data = (char *) (packet + (sizeof(struct iphdr)));
ip_header->version = 4; // IPv4
ip_header->tos = 0; // Type of service
ip_header->ihl = 5; // 5 x 32-bit words
// ip_header->tot_len = htons(sizeof(struct iphdr) + strlen(data)); // Total IP packet length
ip_header->tot_len = sizeof(packet); // Total IP packet length
ip_header->protocol = IPPROTO_IPV6; // 6in4 protocol
ip_header->frag_off = 0x00; //16 bit field = [0:2] flags + [3:15] offset = 0x0
ip_header->ttl = 0xFF; // Max number of hops 16bit
// ip_header->id = htons(54321); // 0x00; //16 bit id
ip_header->check = 0; //16 bit checksum of IP header. Can't calculate at this point
ip_header->saddr = inet_addr(srcIP);
ip_header->daddr = inet_addr(dstIP);
data[0] = 'T';
data[1] = 'E';
data[2] = 'S';
data[3] = 'T';
data[4] = '7';
data[5] = '\0';
// ip_header->check = csum((unsigned short *) packet, ip_header->tot_len);
#if DEBUG
printf("\nIP header checksum: %d\n", ip_header->check);
#endif
while (1) {
sleep(1);
if (sendto(socket_fd, (char *) packet, sizeof(packet), 0,
(struct sockaddr *) &daddr, (socklen_t) sizeof(daddr)) < 0)
perror("Packet send error");
}
return 0;
}
Server code:
/*** IPPROTO_RAW receiver ***/
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int socket_fd;
struct sockaddr_in saddr;
char packet[50];
if ((socket_fd = socket(AF_INET, SOCK_RAW, IPPROTO_IPV6)) < 0) {
perror("socket_fd");
exit(EXIT_FAILURE);
}
memset(packet, 0, sizeof(packet));
socklen_t len = (socklen_t) sizeof(saddr);
while(1) {
if (recvfrom(socket_fd, packet, sizeof(packet), 0,
(struct sockaddr *)&saddr, &len) < 0)
perror("recvfrom");
int i = sizeof(struct iphdr); ////// WHY IS DATA PAYLOAD ON packet[sizeof(struct iphdr) * 2]
while (i < sizeof(packet)) {
fprintf(stderr, "%c", packet[i]);
i++;
}
printf("\n");
}
exit(EXIT_SUCCESS);
}

In your sender, you need to set the IP_HDRINCL socket option. That tells the API that you're manually supplying the IP header. Because you're not setting this option, you're effectively putting your own copy of the IP header after the one the system adds.

IP_HDRINCL socket option is normally implicitly set only in the case of usage of IPPROTO_RAW. If you are not using IPPROTO_RAW, then the header will be generated as IP_HDRINCL will not be set implicitly.
Refer to man7.org/linux/man-pages/man7/raw.7.html.

Related

AF_PACKET Socket Not Sending Empty UDP Packet With SOCK_RAW In C

I am trying to create a test program in C on Linux (Ubuntu 18.04) that sends an empty UDP packet via an AF_PACKET/PF_PACKET socket using SOCK_RAW. In this program, I know the source and destination MAC addresses and IPs. However, it is not working and I'm not sure what I'm doing wrong. I wasn't able to find much resources online regarding this issue sadly since most of the threads I've found are more so for receiving packets on AF_PACKET sockets. The program also states it sends the correct amount of bytes to the destination. Though, I don't see the packets when using tcpdump both on the source and destination VMs.
Here is the program's code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <linux/if.h>
#include <linux/if_packet.h>
#include <linux/udp.h>
#include <net/ethernet.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include <inttypes.h>
#define REDIRECT_HEADER
#include "csum.h"
#define MAX_PCKT_LENGTH 65535
int main()
{
int sockfd;
struct sockaddr_ll dst;
char pckt[MAX_PCKT_LENGTH];
sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
if (sockfd <= 0)
{
perror("socket");
exit(1);
}
dst.sll_family = AF_PACKET;
dst.sll_protocol = ETH_P_IP;
if ((dst.sll_ifindex = if_nametoindex("ens18")) == 0)
{
fprintf(stdout, "Interface 'ens18' not found.\n");
exit(1);
}
// Do destination ethernet MAC (ae:21:14:4b:3a:6d).
dst.sll_addr[0] = 0xAE;
dst.sll_addr[1] = 0x21;
dst.sll_addr[2] = 0x14;
dst.sll_addr[3] = 0x4B;
dst.sll_addr[4] = 0x3A;
dst.sll_addr[5] = 0x6D;
dst.sll_halen = 6;
// I tried doing this with and without bind. Still not working.
if (bind(sockfd, (struct sockaddr *)&dst, sizeof(dst)) < 0)
{
perror("bind");
exit(1);
}
struct ethhdr *ethhdr = (struct ethhdr *) (pckt);
struct iphdr *iphdr = (struct iphdr *) (pckt + sizeof(struct ethhdr));
struct udphdr *udphdr = (struct udphdr *) (pckt + sizeof(struct ethhdr) + sizeof(struct iphdr));
unsigned char *data = (unsigned char *) (pckt + sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct udphdr));
// Do source ethernet MAC (1a:c4:df:70:d8:a6).
ethhdr->h_source[0] = 0x1A;
ethhdr->h_source[1] = 0xC4;
ethhdr->h_source[2] = 0xDF;
ethhdr->h_source[3] = 0x70;
ethhdr->h_source[4] = 0xD8;
ethhdr->h_source[5] = 0xA6;
// Copy destination MAC to sockaddr_ll.
memcpy(ethhdr->h_dest, dst.sll_addr, 6);
// Protocol.
ethhdr->h_proto = ETH_P_IP;
// Fill out ip header.
iphdr->ihl = 5;
iphdr->version = 4;
iphdr->frag_off = 0;
iphdr->id = rand();
iphdr->protocol = IPPROTO_UDP;
iphdr->tos = 0x0;
iphdr->ttl = 64;
iphdr->saddr = inet_addr("10.50.0.3");
iphdr->daddr = inet_addr("10.50.0.4");
iphdr->tot_len = sizeof(struct iphdr) + sizeof(struct udphdr);
iphdr->check = 0;
iphdr->check = ip_fast_csum(iphdr, iphdr->ihl);
// Fill out UDP header.
udphdr->source = htons(27000);
udphdr->dest = htons(27015);
udphdr->len = htons(sizeof(struct udphdr));
udphdr->check = 0;
udphdr->check = csum_tcpudp_magic(iphdr->saddr, iphdr->daddr, sizeof(struct udphdr), IPPROTO_UDP, csum_partial(udphdr, sizeof(struct udphdr), 0));
// Send packet
uint16_t sent;
if ((sent = sendto(sockfd, pckt, iphdr->tot_len + sizeof(struct ethhdr), 0, (struct sockaddr *)&dst, sizeof(dst))) < 0)
{
perror("sendto");
}
fprintf(stdout, "Sent %d of data.\n", sent);
close(sockfd);
exit(0);
}
Both the source and destination servers are VMs on my home server (both running Ubuntu 18.04).
Here is the main interface of my source VM:
ens18: flags=323<UP,BROADCAST,RUNNING,PROMISC> mtu 1500
inet 10.50.0.3 netmask 255.255.255.0 broadcast 10.50.0.255
inet6 fe80::18c4:dfff:fe70:d8a6 prefixlen 64 scopeid 0x20<link>
ether 1a:c4:df:70:d8:a6 txqueuelen 1000 (Ethernet)
RX packets 1959766813 bytes 1896024793559 (1.8 TB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1936101432 bytes 1333123918522 (1.3 TB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Here is the main interface of my destination VM:
ens18: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.50.0.4 netmask 255.255.255.0 broadcast 10.50.0.255
inet6 fe80::ac21:14ff:fe4b:3a6d prefixlen 64 scopeid 0x20<link>
ether ae:21:14:4b:3a:6d txqueuelen 1000 (Ethernet)
RX packets 1032069029 bytes 1251754298166 (1.2 TB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 74446483 bytes 9498785163 (9.4 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
I tried setting the source VM's 'ens18' interface to promiscuous mode, but that didn't make any difference. I don't think that would matter in this case, though. I also want to use SOCK_RAW in this case because I want to gain more experience and I don't want the kernel to do anything to the packets (I read that using AF_PACKET + SOCK_RAW will result in the kernel not messing with the packets).
With that said, I have an additional question. How would I go about getting the MAC address of an IP that isn't on the network/bound to an interface (e.g. a destination IP going to a server outside of my network)? I would assume I'd have to send an ARP request. If so, do I just send an ARP request to the destination server and get the MAC address before submitting each packet via AF_PACKET + SOCK_RAW?
Any help is highly appreciated and thank you for your time!
I was able to figure out the issue. I wasn't converting the Ethernet protocol (ETH_P_IP) to network byte order via htons() since it's a big endian. With that said, I had to convert iphdr->total_len to network byte order as well. Otherwise, the IP header's total length would be incorrect according to tcpdump. I didn't do this in other programs I made and it worked okay. Therefore, I'd assume the kernel converted the IP header's total length to network byte order automatically.
Since I'm using an AF_PACKET socket to send, I have to do things the kernel would normally do.
Here's the program's final code for anyone wondering:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <linux/if.h>
#include <linux/if_packet.h>
#include <linux/udp.h>
#include <net/ethernet.h>
#include <string.h>
#include <error.h>
#include <errno.h>
#include <inttypes.h>
#define REDIRECT_HEADER
#include "csum.h"
#define MAX_PCKT_LENGTH 65535
int main()
{
int sockfd;
struct sockaddr_ll dst;
char pckt[MAX_PCKT_LENGTH];
sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);
if (sockfd <= 0)
{
perror("socket");
exit(1);
}
dst.sll_family = PF_PACKET;
dst.sll_protocol = htons(ETH_P_IP);
if ((dst.sll_ifindex = if_nametoindex("ens18")) == 0)
{
fprintf(stdout, "Interface 'ens18' not found.\n");
exit(1);
}
// Do destination ethernet MAC (ae:21:14:4b:3a:6d).
dst.sll_addr[0] = 0xAE;
dst.sll_addr[1] = 0x21;
dst.sll_addr[2] = 0x14;
dst.sll_addr[3] = 0x4B;
dst.sll_addr[4] = 0x3A;
dst.sll_addr[5] = 0x6D;
dst.sll_halen = ETH_ALEN;
// I tried doing this with and without bind. Still not working.
if (bind(sockfd, (struct sockaddr *)&dst, sizeof(dst)) < 0)
{
perror("bind");
exit(1);
}
struct ethhdr *ethhdr = (struct ethhdr *) (pckt);
struct iphdr *iphdr = (struct iphdr *) (pckt + sizeof(struct ethhdr));
struct udphdr *udphdr = (struct udphdr *) (pckt + sizeof(struct ethhdr) + sizeof(struct iphdr));
unsigned char *data = (unsigned char *) (pckt + sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct udphdr));
// Do source ethernet MAC (1a:c4:df:70:d8:a6).
ethhdr->h_source[0] = 0x1A;
ethhdr->h_source[1] = 0xC4;
ethhdr->h_source[2] = 0xDF;
ethhdr->h_source[3] = 0x70;
ethhdr->h_source[4] = 0xD8;
ethhdr->h_source[5] = 0xA6;
for (int i = 0; i < 30; i++)
{
memcpy(data + i, "b", 1);
}
// Copy destination MAC to sockaddr_ll.
memcpy(ethhdr->h_dest, dst.sll_addr, ETH_ALEN);
// Protocol.
ethhdr->h_proto = htons(ETH_P_IP);
// Fill out ip header.
iphdr->ihl = 5;
iphdr->version = 4;
iphdr->frag_off = 0;
iphdr->id = htons(0);
iphdr->protocol = IPPROTO_UDP;
iphdr->tos = 0x0;
iphdr->ttl = 64;
iphdr->saddr = inet_addr("10.50.0.3");
iphdr->daddr = inet_addr("10.50.0.4");
iphdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct udphdr) + 30);
iphdr->check = 0;
iphdr->check = ip_fast_csum(iphdr, iphdr->ihl);
// Fill out UDP header.
udphdr->source = htons(27000);
udphdr->dest = htons(27015);
udphdr->len = htons(sizeof(struct udphdr) + 30);
udphdr->check = 0;
udphdr->check = csum_tcpudp_magic(iphdr->saddr, iphdr->daddr, sizeof(struct udphdr) + 30, IPPROTO_UDP, csum_partial(udphdr, sizeof(struct udphdr) + 30, 0));
// Send packet
uint16_t sent;
int len = ntohs(iphdr->tot_len) + sizeof(struct ethhdr) + 30;
if ((sent = sendto(sockfd, pckt, len, 0, (struct sockaddr *)&dst, sizeof(dst))) < 0)
//if ((sent = write(sockfd, pckt, len)) < 0)
{
perror("sendto");
}
fprintf(stdout, "Sent %d of data. %d is IPHdr len. %d is len.\n", sent, iphdr->tot_len, len);
close(sockfd);
exit(0);
}

Custom IP header for ICMP packet not working

I'm trying to make an ICMP packet with a custom IP header.
When I disable IP_HDRINCL to use the default IP header and cut out all the IP header related code, it works (I checked the checksums of the code below and the code that works with default headers, the ICMP packet is definitely valid in the code below).
The issue arrives when trying to use my own IP header, I don't receive any ICMP packets, indicating the packet didn't properly transmit or something went wrong.
I'm on Ubuntu 16.04 and compiling with GCC with the flags -std=c11 -Wall -Wextra -pedantic
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <arpa/inet.h>
#define PACKETSIZE 256
// Packet struct
struct packet {
struct iphdr ip; // IP Header
struct icmphdr hdr; // ICMP Header
char msg[PACKETSIZE - sizeof(struct icmphdr) - sizeof(struct iphdr)]; // Message
};
// Checksum function
unsigned short checksum(void *b, int len) {
unsigned short *buf = b;
unsigned int sum = 0;
unsigned short result;
for (sum = 0; len > 1; len -= 2) {
sum += *buf++;
}
if (len == 1) sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
int main(int argc, char* argv[])
{
// Enough arguments
if (argc < 2) {
printf("usage: ./tracert <server>\n");
return EXIT_FAILURE;
}
// Variables
struct hostent *hname;
struct sockaddr_in addr;
unsigned int i;
int sockfd, seq = 1;
struct packet pckt;
socklen_t len;
char buf[1024];
// Get host from domain
hname = gethostbyname(argv[1]);
memset(&addr, 0, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = htons(6969);
addr.sin_addr.s_addr = *(long *)hname->h_addr_list[0];
// Create ICMP RAW socket
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
printf("error on socket creation\n");
return EXIT_FAILURE;;
}
if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &seq, sizeof(seq)) < 0) {
printf("error on default ip header settings\n");
return EXIT_FAILURE;
}
// Loop and receive/send packets
while (1) {
// Make packet
memset(&pckt, 0, sizeof(pckt));
// IP Header
pckt.ip.version = 4;
pckt.ip.ihl = 5;
pckt.ip.tot_len = htons(sizeof(pckt));
pckt.ip.ttl = 255;
pckt.ip.protocol = IPPROTO_ICMP;
pckt.ip.saddr = inet_addr("192.168.1.1");
pckt.ip.daddr = addr.sin_addr.s_addr;
pckt.ip.check = checksum(&pckt, sizeof(struct iphdr));
// ICMP Header
pckt.hdr.type = ICMP_ECHO;
pckt.hdr.un.echo.id = 0;
for (i = 0; i < sizeof(pckt.msg) - 1; i++) {
pckt.msg[i] = i+'0';
}
pckt.msg[i] = 0;
pckt.hdr.un.echo.sequence = seq;
pckt.hdr.checksum = checksum(&pckt.hdr, sizeof(struct icmphdr) + sizeof(pckt.msg));
// Send packet
if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&addr, sizeof(addr)) <= 0) {
printf("error on sending packet\n");
return EXIT_FAILURE;
}
// Receive packet
len = sizeof(addr);
memset(buf, 0, sizeof(buf));
if (recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &len) > 0) {
printf("packet received\n");
// Do more stuff here later...
}
// The while is there for later, for now I just want to send one packet
return EXIT_SUCCESS;
}
close(sockfd);
return EXIT_SUCCESS;
}

The empty filed about IP packet

I'm a new starter of Linux C and try to make a program about make a IP packet, it's like a simple DoS tool. When I finish the code, I captured the packet and analysed the packet with Wireshark, the IP version is 0 and the header length is 0, too. why it happened.
I haven't add the checksum part.
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <strings.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char **argv[])
{
char buffer[100];
struct sockaddr_in addr;
struct ip *ip;
struct tcphdr *tcp;
int head_len,sockfd, on = 1;
head_len = sizeof (struct ip) + sizeof (struct tcphdr);
bzero(buffer,100);
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = inet_addr("10.3.1.25");
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
setsockopt(sockfd,IPPROTO_IP, IP_HDRINCL, &on,sizeof(on));
ip->ip_v = IPVERSION;
ip->ip_hl = sizeof(struct ip)>>2;
ip->ip_tos = 0;
ip->ip_len = htons(head_len);
ip->ip_id = 0;
ip->ip_off = 0;
ip->ip_ttl = 255;
ip->ip_p = IPPROTO_TCP;
ip->ip_src.s_addr = random();
ip->ip_dst = addr.sin_addr;
tcp = (struct tcphdr *)(buffer + sizeof(struct ip));
tcp->source = htons(8888);
tcp->dest = addr.sin_port;
tcp->seq = random();
tcp->ack_seq = 0;
tcp->doff = 5;
tcp->syn = 1;
tcp->check = 0;
setuid(getpid());
sizeof(struct tcphdr());
printf("phase 3 ok\n");
while (1)
{
if(sendto (sockfd, buffer, head_len, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 1)
printf("error");
}
}
You forgot to initialise ip; I'm assuming you are missing
ip = (struct ip*)buffer;

Raw Socket Linux send/receive a packet

Have some problems in receiving packets.
I can receive and read incoming packets, but I think i do not get a handshake with any host.
I only want to send a packet to a remote computer with an open port on receiving an answer to see the TTL(time to live) and the window size.
Does anyone have an idea where the errors are? (I don't have very deep knowledge in C programming)
CODE:
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
struct pseudohdr {
u_int32_t src_addr;
u_int32_t dst_addr;
u_int8_t padding;
u_int8_t proto;
u_int16_t length;
};
struct data_4_checksum {
struct pseudohdr pshd;
struct tcphdr tcphdr;
char payload[1024];
};
unsigned short comp_chksum(unsigned short *addr, int len) {
long sum = 0;
while (len > 1) {
sum += *(addr++);
len -= 2;
}
if (len > 0)
sum += *addr;
while (sum >> 16)
sum = ((sum & 0xffff) + (sum >> 16));
sum = ~sum;
return ((u_short) sum);
}
int main(int argc, char *argv[]) {
int sock, bytes, on = 1;
char buffer[1024];
struct iphdr *ip;
struct tcphdr *tcp;
struct sockaddr_in to;
struct pseudohdr pseudoheader;
struct data_4_checksum tcp_chk_construct;
if (argc != 2) {
fprintf(stderr, "Usage: %s ", argv[0]);
fprintf(stderr, "<dest-addr>\n");
return 1;
}
sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
if (sock == -1) {
perror("socket() failed");
return 1;
}else{
printf("socket() ok\n");
}
if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) == -1) {
perror("setsockopt() failed");
return 2;
}else{
printf("setsockopt() ok\n");
}
ip = (struct iphdr*) buffer;
tcp = (struct tcphdr*) (buffer + sizeof(struct tcphdr));
int iphdrlen = sizeof(struct iphdr);
int tcphdrlen = sizeof(struct tcphdr);
int datalen = 0;
printf("Typecasting ok\n");
ip->frag_off = 0;
ip->version = 4;
ip->ihl = 5;
ip->tot_len = htons(iphdrlen + tcphdrlen);
ip->id = 0;
ip->ttl = 40;
ip->protocol = IPPROTO_TCP;
ip->saddr = inet_addr("192.168.165.135");
ip->daddr = inet_addr(argv[1]);
ip->check = 0;
tcp->source = htons(12345);
tcp->dest = htons(80);
tcp->seq = random();
tcp->doff = 5;
tcp->ack = 0;
tcp->psh = 0;
tcp->rst = 0;
tcp->urg = 0;
tcp->syn = 1;
tcp->fin = 0;
tcp->window = htons(65535);
pseudoheader.src_addr = ip->saddr;
pseudoheader.dst_addr = ip->daddr;
pseudoheader.padding = 0;
pseudoheader.proto = ip->protocol;
pseudoheader.length = htons(tcphdrlen + datalen);
tcp_chk_construct.pshd = pseudoheader;
tcp_chk_construct.tcphdr = *tcp;
int checksum = comp_chksum((unsigned short*) &tcp_chk_construct,
sizeof(struct pseudohdr) + tcphdrlen + datalen);
tcp->check = checksum;
printf("TCP Checksum: %i\n", checksum);
printf("Destination : %i\n", ntohs(tcp->dest));
printf("Source: %i\n", ntohs(tcp->source));
to.sin_addr.s_addr = ip->daddr;
to.sin_family = AF_INET;
to.sin_port = tcp->dest;
bytes = sendto(sock, buffer, ntohs(ip->tot_len), 0, (struct sockaddr*) &to,
sizeof(to));
if (bytes == -1) {
perror("sendto() failed");
return 1;
}
recv(sock, buffer, sizeof(buffer), 0);
printf("TTL= %d\n", ip->ttl);
printf("Window= %d\n", tcp->window);
printf("ACK= %d\n", tcp->ack);
printf("%s:%d\t --> \t%s:%d \tSeq: %d \tAck: %d\n",
inet_ntoa(*(struct in_addr*) &ip->saddr), ntohs(tcp->source),
inet_ntoa(*(struct in_addr *) &ip->daddr), ntohs(tcp->dest),
ntohl(tcp->seq), ntohl(tcp->ack_seq));
return 0;
}
You're receiving and storing packets in buffer, but you're printing data from ip and tcp without parsing that buffer. You should parse the packet from buffer after receiving it, and before printing.
Your code assumes all packets are TCP, which is not the case. RAW sockets only support Layer 3 protocols (IP, ICMP, etc). In other words, using IPPROTO_TCP is misleading when creating a RAW socket. Stick to IPPROTO_IP, and add the necessary conditions to your code for each protocol you care about (TCP, UDP, etc). This happens to be working because the Linux Kernel validates the protocol number, and fallbacks to IPPROTO_IP. However, this might not work in other systems.
Review if your network communication is using the correct byte-order. The network-byte-order is Big-Endian, while the host-byte-order depends on your architecture, so you may need to convert multi-byte fields back and forth.
Your tcp->seq might have an invalid value, because TCP only accepts values up to 65535, while random() returns values from 0 to RAND_MAX (0x7fffffff). Try tcp->seq = htonl(random() % 65535);
Your offset calculation for the TCP header is incorrect. It should be sizeof(struct iphdr) rather than sizeof(struct tcphdr).
ip = (struct iphdr*) buffer;
tcp = (struct tcphdr*) (buffer + sizeof(struct tcphdr)); //This is wrong
Here to get array index of tcp header in buffer, you need to add sizeof(struct iphdr) to buffer like mentioned below.
ip = (struct iphdr*) buffer;
tcp = (struct tcphdr*) (buffer + sizeof(struct iphdr)); //This is correct

socket error when using SOCK_RAW and how to accept multiple client with layer 2 communication

soc = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); in client side, when run, get == -1 error
if accept function can only use with UDP and TCP higher protocol, how to accept multiple client with layer 2 communication?
where can find the code of accept function, i would like to rewrite it for layer 2.
Updated :
After tried soc = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
also == -1 , get this error
server side and client side both are the same computer, local one
strange is that running server side, it do not have this error, but running client program got error
//#include "stdafx.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netpacket/packet.h>
#include <net/ethernet.h>
#include <netinet/ether.h>
//#include "sock.h"
#define MAX_MESSAGE 21000
#define FD_NUM 5
#define tcp_port 5009
//#pragma comment(lib, "ws2_32.lib")
//#include <winsock2.h>
char host_ip[16] = "127.0.0.1";
void task()
{
struct sockaddr_in local;
int opt;
int soc;
//soc = socket(AF_INET,SOCK_STREAM,0);
soc = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (soc==-1) {
printf("socket error\n");
}
// determine ethernet number
/*
struct ifreq ifr;
size_t if_name_len=strlen(if_name);
if (if_name_len<sizeof(ifr.ifr_name)) {
memcpy(ifr.ifr_name,if_name,if_name_len);
ifr.ifr_name[if_name_len]=0;
} else {
printf("interface name is too long");
}
if (ioctl(fd,SIOCGIFINDEX,&ifr)==-1) {
printf("determine ethernet number error\n");
}
int ifindex=ifr.ifr_ifindex;
*/
// mac address
/*target address*/
struct sockaddr_ll socket_address;
/*buffer for ethernet frame*/
void* buffer = (void*)malloc(ETH_FRAME_LEN);
/*pointer to ethenet header*/
unsigned char* etherhead = (unsigned char*)buffer;
/*userdata in ethernet frame*/
unsigned char* data = (unsigned char*)buffer + 14;
/*another pointer to ethernet header*/
struct ethhdr *eh = (struct ethhdr *)etherhead;
int send_result = 0;
/*our MAC address*/
//10:78:d2:ad:90:cb
//0x10,0x78,0xD2,0xAD,0x90,0xCB
unsigned char src_mac[6] = {0x10,0x78,0xD2,0xAD,0x90,0xCB};
/*other host MAC address*/
unsigned char dest_mac[6] = {0x10,0x78,0xD2,0xAD,0x90,0xCB};
/*prepare sockaddr_ll*/
/*RAW communication*/
socket_address.sll_family = PF_PACKET;
/*we don't use a protocoll above ethernet layer
->just use anything here*/
socket_address.sll_protocol = htons(ETH_P_IP);
/*index of the network device
see full code later how to retrieve it*/
socket_address.sll_ifindex = 0;
/*ARP hardware identifier is ethernet*/
socket_address.sll_hatype = ARPHRD_ETHER;
/*target is another host*/
socket_address.sll_pkttype = PACKET_OTHERHOST;
/*address length*/
socket_address.sll_halen = ETH_ALEN;
/*MAC - begin*/
socket_address.sll_addr[0] = 0x10;
socket_address.sll_addr[1] = 0x78;
socket_address.sll_addr[2] = 0xD2;
socket_address.sll_addr[3] = 0xAD;
socket_address.sll_addr[4] = 0x90;
socket_address.sll_addr[5] = 0xCB;
/*MAC - end*/
socket_address.sll_addr[6] = 0x00;/*not used*/
socket_address.sll_addr[7] = 0x00;/*not used*/
memcpy((void*)buffer, (void*)dest_mac, ETH_ALEN);
memcpy((void*)(buffer+ETH_ALEN), (void*)src_mac, ETH_ALEN);
eh->h_proto = 0x00;
int j = 0;
for (j = 46; --j; data[j] = (unsigned char)((int) (255.0*rand()/(RAND_MAX+1.0))));
/*
struct sockaddr_in server;
int len = sizeof(server);
server.sin_family=AF_INET;
server.sin_port=htons(5008);
server.sin_addr.s_addr=inet_addr(host_ip);
int CONN_SOCK = InitSocketTcp(tcp_port);
if(connect(CONN_SOCK, (struct sockaddr*)&server, sizeof(server)) == -1)
{
printf("connection failed\n");
}
else
{
printf("connection ok!\n");
}
*/
while(1)
{
char buff[492] = "\0";
printf("input: ");
scanf("%s", buff);
//send(CONN_SOCK,buff,strlen(buff),0);
/*send the packet*/
send_result = sendto(soc, buff, ETH_FRAME_LEN, 0, (struct sockaddr*)&socket_address, sizeof(socket_address));
send_result == -1?printf("send error"):0;
if(buff[0] == 'q')
{
//shutdown(CONN_SOCK, SD_SEND);
//closesocket(CONN_SOCK);
//WSACleanup();
close(soc);
exit(0);
}
}
}
int main()
{
//for(int i=10; i!=0; --i)
//pthread_create();
task();
return 0;
}
Accept() is only used for TCP or UDP (practically it's main use is in tcp), because it establishes a connection. A connection does 3 way handshake in case of tcp and exchanges information such as sequence numbers etc. and is completely identified by a socket (port plus ip address)
In contrast to that you can simply use sendto and receivefrom api's as normally used in case of udp, where each packet may follow a different path to reach destination. You do not require an accept in case of udp communication. The same can be extended to link layer (L2) frames i.e. each side can send or receive at will without actually establishing a connection first.
This should be done using root

Resources