#include <iostream>
#include <string>
#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using std::cout;
using std::endl;
using std::exception;
int main(int argc, char **argv)
{
if(argc != 4)
{
cout << "Usage: " << argv[0] << " Host Port String" << endl;
return -1;
}
try
{
struct sockaddr_in serverAddr;
struct sockaddr recvAddr;
socklen_t iSockLen = 0; // mark
//socklen_t iSockLen = sizeof(struct sockaddr_in); // mark
char buf[128] = {0};
int bufLen = snprintf(buf, sizeof(buf), "%s", argv[3]);
int sockFd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockFd < 0)
return -1;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
int ret = sendto(sockFd, buf, bufLen, 0,
(const struct sockaddr *)&serverAddr, sizeof(serverAddr));
cout << "send count:" << ret << " data:" << buf << endl;
bzero(buf, sizeof(buf));
ret = recvfrom(sockFd, buf, sizeof(buf), 0,
(struct sockaddr *)&recvAddr, (socklen_t *)&iSockLen); //mark
cout << "recv count:" << ret << " data:" << buf
<< " errno:" << strerror(errno) << endl;
}
catch(exception &e)
{
cout << "SocketException: " << e.what() << endl;
}
return 0;
}
#include <string>
#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using std::cout;
using std::endl;
using std::exception;
int main(int argc, char **argv)
{
if(argc != 4)
{
cout << "Usage: " << argv[0] << " Host Port String" << endl;
return -1;
}
try
{
struct sockaddr_in serverAddr;
struct sockaddr recvAddr;
socklen_t iSockLen = 0; // mark
//socklen_t iSockLen = sizeof(struct sockaddr_in); // mark
char buf[128] = {0};
int bufLen = snprintf(buf, sizeof(buf), "%s", argv[3]);
int sockFd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockFd < 0)
return -1;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
int ret = sendto(sockFd, buf, bufLen, 0,
(const struct sockaddr *)&serverAddr, sizeof(serverAddr));
cout << "send count:" << ret << " data:" << buf << endl;
bzero(buf, sizeof(buf));
ret = recvfrom(sockFd, buf, sizeof(buf), 0,
(struct sockaddr *)&recvAddr, (socklen_t *)&iSockLen); //mark
cout << "recv count:" << ret << " data:" << buf
<< " errno:" << strerror(errno) << endl;
}
catch(exception &e)
{
cout << "SocketException: " << e.what() << endl;
}
return 0;
}