1.Server.cpp
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
// if(argc <= 2)
// {
// cout<<"please enter more args"<<endl;
// return 0;
// }
// int port = atoi(argv[1]);
// char* ip = argv[2];
int port = 5566;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
assert(sock >= 0);
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl( INADDR_ANY );
//inet_pton(AF_INET, ip, &addr.sin_addr); //if do you can use telnet
int ret = bind(sock, (struct sockaddr*)&addr, sizeof(addr));
assert(ret == 0);
struct sockaddr_in acceptaddr;
unsigned int len = sizeof(acceptaddr);
char recvbuf[128] = {'\0'};
while(true)
{
ret = recvfrom(sock, recvbuf, 128, 0, (struct sockaddr*)&acceptaddr, &len);
cout<<"buf is: "<<recvbuf<<endl;
assert(ret > 0);
ret = sendto(sock, recvbuf, 128, 0, (struct sockaddr*)&acceptaddr, len);
assert(ret > 0);
}
close(sock);
return 1;
}
2.client.cpp
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
if(argc <= 2)
{
cout<<"please enter more args"<<endl;
return 0;
}
char* ip = argv[1];
int port = atoi(argv[2]);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
assert(sock >= 0);
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &addr.sin_addr);
const char *buf = "This is a test from jack";
int ret = sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&addr, sizeof(addr));
assert(ret > 0);
struct sockaddr_in acceptaddr;
unsigned int len = sizeof(acceptaddr);
char recvbuf[128] = { '\0' };
ret = recvfrom(sock, recvbuf, 128, 0, (struct sockaddr*)&acceptaddr, &len);
assert(ret > 0);
cout<<"recv "<<ret<<" bytes, buf is: "<<recvbuf<<endl;
close(sock);
return 1;
}