主题:winsock编程bind失败~~高手指教啊
这是一个绑定raw socket到本机的小程序,运行总是会提示 "bind failed"也就是绑定失败。socket与WSAstartup返回都正常,到底是怎么回事呢?
#include <stdio.h>
//#include "ws2tcpip.h"为什么这句加上去就会有好几十个错误出现这有是为什么呢?
#include "winsock2.h"
#include "windows.h"
#pragma comment(lib, "ws2_32.lib")
void main()
{
struct hostent *pHostIP;
struct sockaddr_in addr_in;
WSADATA wsaData;
char hostname[128];
SOCKET sock;
BOOL flag= TRUE;
int err;
char buf[65535];
DWORD dwValue = 1;
err = WSAStartup(MAKEWORD(2,2),&wsaData);
if(err!=0) printf(" WSAStartup failed \n");
gethostname(hostname,128);
if((pHostIP = gethostbyname(hostname)) == NULL) {
printf("\nGet hostbyname failed!\n");
}
//建立原始socket
if(sock=(socket(AF_INET,SOCK_RAW,IPPROTO_IP))==INVALID_SOCKET) {
printf( "create socket failed!\n ");
}
addr_in.sin_addr = *(struct in_addr*)pHostIP -> h_addr_list[0];
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(6000);
//把原始socket绑定到本地网卡上 sin_addr.S_un.S_ad
if((bind(sock,(PSOCKADDR)&addr_in, sizeof(addr_in)))==SOCKET_ERROR) {
printf( "bind failed ");
}
recv( sock, buf, 65535, 0);
WSAGetLastError() ;
printf("%s\n", hostname);
WSACleanup();
#include <stdio.h>
//#include "ws2tcpip.h"为什么这句加上去就会有好几十个错误出现这有是为什么呢?
#include "winsock2.h"
#include "windows.h"
#pragma comment(lib, "ws2_32.lib")
void main()
{
struct hostent *pHostIP;
struct sockaddr_in addr_in;
WSADATA wsaData;
char hostname[128];
SOCKET sock;
BOOL flag= TRUE;
int err;
char buf[65535];
DWORD dwValue = 1;
err = WSAStartup(MAKEWORD(2,2),&wsaData);
if(err!=0) printf(" WSAStartup failed \n");
gethostname(hostname,128);
if((pHostIP = gethostbyname(hostname)) == NULL) {
printf("\nGet hostbyname failed!\n");
}
//建立原始socket
if(sock=(socket(AF_INET,SOCK_RAW,IPPROTO_IP))==INVALID_SOCKET) {
printf( "create socket failed!\n ");
}
addr_in.sin_addr = *(struct in_addr*)pHostIP -> h_addr_list[0];
addr_in.sin_family = AF_INET;
addr_in.sin_port = htons(6000);
//把原始socket绑定到本地网卡上 sin_addr.S_un.S_ad
if((bind(sock,(PSOCKADDR)&addr_in, sizeof(addr_in)))==SOCKET_ERROR) {
printf( "bind failed ");
}
recv( sock, buf, 65535, 0);
WSAGetLastError() ;
printf("%s\n", hostname);
WSACleanup();