目前我正在编写一个程序,该程序应通过 UDP 接收来自另一台电脑的消息并将另一条消息发送回这台电脑。正在接收消息,但是当我想发回消息时,在创建套接字时出现(套接字)错误。那么,为什么我会收到错误消息,我的代码在其他部分是否也有错误?
SOCKET recv, trans;
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return 1;
}
char myname[256], yourname[256];
struct sockaddr_in sa_recv, sa_trans;
struct hostent *hp_recv, *hp_trans;
memset(&sa_recv, 0, sizeof(struct sockaddr_in)); /* clear our address */
memset(&sa_trans, 0, sizeof(struct sockaddr_in));
gethostname(myname, sizeof(myname)); /* who are we? */
hp_recv = gethostbyname("localhost"); /* get our address info */
//std::cout << hp_recv->h_addrtype << ' ' << hp_recv->h_addr_list << ' ' << hp_recv->h_aliases << ' ' << hp_recv->h_length << ' ' << hp_recv->h_name << ' \n';
if (hp_recv == NULL) /* we don't exist !? */
return(INVALID_SOCKET);
sa_recv.sin_family = hp_recv->h_addrtype; /* this is our host address */
sa_recv.sin_port = htons(PORTNUM); /* this is our port number */
recv = socket(AF_INET, SOCK_DGRAM, 0); /* create the socket */
if (recv == INVALID_SOCKET)
return INVALID_SOCKET;
/* bind the socket to the internet address */
if (bind(recv, (struct sockaddr *)&sa_recv, sizeof(struct sockaddr_in)) ==
SOCKET_ERROR)
{
closesocket(recv);
return(INVALID_SOCKET);
}
struct sockaddr from;
int fromlen = sizeof(from);
char inStr[100];
int ret = recvfrom(recv, inStr, sizeof(inStr), 0, &from, &fromlen);
in_addr * addr = (in_addr * )get_in_addr(&from);
std::cout << "Received " << inStr << " from " << inet_ntoa(*addr);
std::cout << '\n';
closesocket(recv);
std::cout << "Sending Data to " << inet_ntoa(*addr) << '\n';
char *ip = NULL;
ip = (char *) get_in_addr(&from);
/*if (from.sa_family == AF_INET)
{
struct sockaddr_in *sin = (struct sockaddr_in *) from;
ip = inet_ntoa(sin->sin_addr);
};*/
gethostname(yourname, sizeof(yourname));
/*hp_trans = gethostbyname(ip);
if(hp_trans == NULL)
{
std::cerr << "hp_trans is zero " << hp_trans << " from " << hp_recv << " and " << &from << '\n';
getchar();
return(INVALID_SOCKET);
};*/
memset(&sa_trans,0,sizeof(sa_trans));
memcpy((char *)&sa_trans.sin_addr, ip, hp_recv->h_length); /* set address */
sa_trans.sin_family = AF_INET;
sa_trans.sin_port = htons(50001);
trans = socket(AF_INET, SOCK_DGRAM, 0);
if(trans == INVALID_SOCKET)
{
std::cerr << "Trans is an invalid socket " << '\n';
getchar();
return INVALID_SOCKET;
};
if(bind(trans, (struct sockaddr *)&sa_trans, sizeof(struct sockaddr_in)) == SOCKET_ERROR)
{
closesocket(trans);
std::cout << "bind has failed with error " << WSAGetLastError() << '\n';
getchar();
return(INVALID_SOCKET);
};
char str[100] = "Message transmitted. Transmission finished.";
int transmit = sendto(trans, str, sizeof(str), 0, (struct sockaddr *)&sa_trans, sizeof(sa_trans));
std::cout << "Transmission finished. Program will exit. " << '\n';
std::getchar();
return 1;
非常感谢您!