#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <mstcpip.h>
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
std::string getSystemError(int error_code, bool is_chiness_lang)
{
LPVOID strbuffer = NULL;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_code,
MAKELANGID(is_chiness_lang ? LANG_CHINESE : LANG_ENGLISH, is_chiness_lang ? SUBLANG_CHINESE_SIMPLIFIED : SUBLANG_ENGLISH_US), (LPSTR)&strbuffer, 0, NULL);
string ret = (strbuffer == NULL) ? "" : (char*)strbuffer;
if (strbuffer)
LocalFree(strbuffer);
return ret;
}
void printError()
{
cerr << getSystemError(WSAGetLastError(),true) << endl;
}
int main()
{
WSADATA winSockData;
SOCKET current_socket;
if (WSAStartup(MAKEWORD(2, 2), &winSockData)!=0)
{
printError();
return 1;
}
if ((current_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IP)) == INVALID_SOCKET)
{
printError();
return 2;
}
sockaddr_in eth_addr = {0};
eth_addr.sin_family = AF_INET;
//eth_addr.sin_port = 0;// for IP it's unusful
eth_addr.sin_addr.S_un.S_addr = inet_addr("192.168.8.101");
if((bind (current_socket,(sockaddr*)ð_addr,sizeof(eth_addr)))==SOCKET_ERROR)
{
printError();
return 3;
}
u_long sio_flag = 1;
u_long value = 0;
if((WSAIoctl (current_socket,SIO_RCVALL,&sio_flag,sizeof(sio_flag),NULL,0,&value,NULL,NULL))==SOCKET_ERROR)
{
printError();
return 4;
}
char *recv_buf = new char[0xFFFF];
int recv_len = 0;
listen(current_socket, 10);
do
{
recv_len = recv(current_socket, recv_buf, 0xFFFF, 0);
if(recv_len>0)
{
cout << "Length:" << recv_len << endl;
cout << "IPV" << (recv_buf[0] >> 4) << endl;
cout << "IPhead-length:" << 4*(recv_buf[0] & 0xf) << endl;
cout << "Total-length:" << (*(unsigned short*)(recv_buf + 2)) << endl;
//cout << "Total-length:" << (*(unsigned short*)(&recv_buf[2])) << endl;
cout << "ID:" << (*(unsigned short*)(&recv_buf[4])) << endl;
cout << "MF:" << (int)(recv_buf[6] & 0x80) << endl;
cout << "TTL:" << ((int)recv_buf[8]) << endl;
cout << "IPPROTO:" << (recv_buf[9] == 6 ? "TCP" : (recv_buf[9] == 17 ? "UDP" :
"other")) << endl;
cout << "SRC_ADDR:" << (inet_ntoa(*(in_addr*)&recv_buf[12])) << endl;
cout << "DST_ADDR:" << (inet_ntoa(*(in_addr*)&recv_buf[16])) << endl;
cout << "---------------------------------------------------------" << endl;
}
} while (recv_len>0);
delete[] recv_buf;
return 0;
}
- 以管理员身份运行
- 可以通过gethostname () 和 gethostbyname ()获得本机ip
char host_name[255];
if (gethostname(host_name, sizeof(host_name))==0)// need call WSAStartup() first
{
struct hostent* hstent=gethostbyname(host_name);
if(hstent)
{
for (int i = 0; i < hstent->h_length;i++)
{
if (hstent->h_addr_list[i])
cout << inet_ntoa(*(in_addr*)hstent->h_addr_list[i]) << endl;
}
}
}