直接gcc或g++编译就OK
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
void error_handling(const char *message);
void send_udp(char*, char*, char*);
void send_tcp(char*, char*, char*);
int main(int argc, char* argv[])
{
char message[] = "111111111111111";
if(argc!=4)
{
printf("Usage : %s <IP> <port> <udp/tcp>\n", argv[0]);
exit(1);
}
char* ip = argv[1];
char* port = argv[2];
if(strcmp(argv[3], "udp") == 0)
{
send_udp(ip, port, message);
}
else if(strcmp(argv[3], "tcp") == 0)
{
send_tcp(ip, port, message);
}
else
{
printf("error:%s\n", argv[3]);
}
return 0;
}
void send_udp(char* ip, char* port, char* message)
{
int sock;
struct sockaddr_in serv_addr;
sock=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(ip);
serv_addr.sin_port=htons(atoi(port));
int len = sizeof(serv_addr);
while(1)
{
printf("send udp data\n");
sendto(sock, message, sizeof(message), 0, (struct sockaddr*)(&serv_addr), len);
sleep(2);
}
}
void send_tcp(char* ip, char* port, char* message)
{
int sock;
struct sockaddr_in serv_addr;
sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(ip);
serv_addr.sin_port=htons(atoi(port));
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1)
error_handling("connect() error!");
int len = sizeof(serv_addr);
while(1)
{
printf("send tcp data\n");
sendto(sock, message, sizeof(message), 0, (struct sockaddr*)(&serv_addr), len);
sleep(2);
}
close(sock);
}
void error_handling(const char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}