c++ ping
Chcel by som naprogramovat ping pri ktorom by sa echo replay vratil na iny stroj. Mam v sieti 2 PC(1.pc 192.168.1.2 ,2.pc 192.168.1.3) a 1 router (192.168.1.1) odoslem ping na router z 192.168.1.2 a echo replay sa vrati na 192.168.1.3 da sa to ? Zatial mi ide iba normalny ping.
Mam nieco take :
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <iomanip>
using namespace std;
unsigned short checksum(unsigned short *addr, int len)
{
register int sum = 0;
u_short answer = 0;
register u_short *w = addr;
register int nleft = len;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(u_char *) (&answer) = *(u_char *) w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return (answer);
}
int
main(int agrc, char * agrv[])
{
hostent *host;
icmphdr *icmp;
iphdr *ip;
int sock;
int ttl=0;
sockaddr_in sendSockAddr;
int i;
unsigned short int pid=getpid();
cout<<"ip addressa ciela"<<agrv[1]<<endl;
if ((host = gethostbyname(agrv[1])) == NULL)
{
cerr<<"hostname"<<endl;
return -1;
}
if (( sock = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP)) == -1)
{
cerr<<"socket"<<endl;
return -2;
}
ttl=1;
setsockopt(sock, SOL_IP, SO_REUSEADDR, &ttl,sizeof(int));
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_port = 11;
sendSockAddr.sin_addr.s_addr = inet_addr("192.168.8.9");
memcpy(&(sendSockAddr.sin_addr), host->h_addr, host->h_length);
icmp = (icmphdr *) malloc (sizeof(icmphdr));
icmp->type = ICMP_ECHO;
icmp->code = 0;
icmp->un.echo.id = pid;
icmp->un.echo.sequence = 1;
icmp->checksum = checksum((unsigned short *)icmp, sizeof(icmphdr));
ip = (iphdr *) malloc (sizeof(iphdr));
ip->ihl = 5;
ip->version = 4;
ip->tos = 0;
ip->tot_len = sizeof(struct iphdr) + sizeof(struct icmphdr);
ip->id = htons(0);
ip->frag_off = 0;
ip->ttl = 255;
ip->protocol = IPPROTO_ICMP;
ip->saddr = inet_addr("192.168.8.9");
ip->check = checksum((unsigned short *)ip, sizeof( iphdr));
for (i=0;i<10;i++)
sendto(sock, (char *)icmp, sizeof(icmphdr), 0, (sockaddr *)&sendSockAddr, sizeof(sockaddr));
close(sock);
return 0;
}
Pre pridávanie komentárov sa musíte prihlásiť.
Čiže to treba spraviť takto: Komp 192.168.1.2 odosiela požiadavku kompu 192.168.1.3 aby pingol router 192.168.1.1. Takže odpoveď na ping sa vráti tomu, kto oň žiadal (192.168.1.3).
a potom to skus oklamat cez http://netcat.sourceforge.net/ ;-) aby ta nebolela hlava z c++ ;-)