Questions about constructing an IP Header

Source: Internet
Author: User
For more information about how to create an IP header-Linux general technology-Linux programming and kernel, see the following. Try to construct a simple IP packet and send it out, but it is always reported as a location where the Segmentation fault is incorrect.
After tracking printf, I have pointed out in the program. I hope you can give me some advice:


# Include
# Include
# Include
# Include
# Include

# Include
# Include

Int main (void)
{
Int s, I, on = 1;
Char buf [200] = {0}; // for store the data
Struct ip * uheader_ip;
Struct sockaddr_in dip;
Struct icmphdr * uheader_icmp = (struct icmphdr *) (uheader_ip + 1 );
Char * sipaddr = "\ xc0 \ xa8 \ x23 \ xa9"; // 192.168.35.169
Char * dipaddr = "\ xc0 \ xa8 \ x24 \ x59"; // 192.168.36.89

// Create a raw_socket
If (s = socket (AF_INET, SOCK_RAW, IPPROTO_UDP) <0 ){
Perror ("socket ");
Exit (1 );
}

Dip. sin_addr.s_addr = inet_addr ("192.168.36.89 ");
Dip. sin_family = AF_INET;
// Set the IP_HDRINCL option, so the user have
// The right to create his own IP header
If (I = setsockopt (s, IPPROTO_IP, IP_HDRINCL, & on, sizeof (on) <0)
{
Perror ("setsocket ");
Exit (1 );
}


// Notice: the big/little order

// Fill the ip header
Uheader_ip = (struct ip *) buf;
Uheader_ip-> ip_hl = 20;
Uheader_ip-> ip_v = 4;
Uheader_ip-> ip_tos = 0;
Uheader_ip> ip_len = 200;
Uheader_ip-> ip_off = 0;
Uheader_ip-> ip_ttl = 255;
Uheader_ip-> ip_p = 1;
// Struct in_addr

// The error location is in these two lines !!
Uheader_ip-> ip_src.s_addr = inet_addr ("192.168.35.169 ");
Uheader_ip-> ip_dst.s_addr = inet_addr ("192.168.36.89 ");


// Fill the icmp header
Uheader_icmp-> type = ICMP_ECHO;
Uheader_icmp-> code = 0;
Uheader_icmp-> checksum = htons (~ (ICMP_ECHO) <8 );

If (sendto (s, buf, sizeof (buf), 0, (struct sockaddr *) & dip, 4 )){
Perror ("sendto ");
}
Return 1;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.