命名管道不能實現局域網內通訊
服務器端建立命名管道:
hPipe=CreateNamedPipe("\\\\.\\pipe\\MyPipe",
PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
0,1,1024,1024,0,NULL);
if(hPipe==INVALID_HANDLE_VALUE)
{
MessageBox("Failed to create named pipe!");
hPipe=NULL;
return;
}
HANDLE hEvent;
hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
if(!hEvent)
{
MessageBox("Failed to create event!");
CloseHandle(hPipe);
hPipe=NULL;
return;
}
OVERLAPPED ovlap;
ZeroMemory(&ovlap,sizeof(OVERLAPPED));
ovlap.hEvent=hEvent;
if(!ConnectNamedPipe(hPipe,&ovlap))
{
if(GetLastError()!=ERROR_IO_PENDING)
{
MessageBox("Failed to wait for client!");
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe=NULL;
return;
}
}
if(WaitForSingleObject(hEvent,INFINITE)==WAIT_FAILED)
{
MessageBox("Failed to wait for event!");
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe=NULL;
return;
}
CloseHandle(hEvent);
客戶端建立命名管道:
if(!WaitNamedPipe("\\\\UT\\pipe\\MyPipe",NMPWAIT_WAIT_FOREVER))
{
MessageBox("No available pipe!");
return;
}
hPipe=CreateFile("\\\\UT\\pipe\\MyPipe",GENERIC_READ|GENERIC_WRITE,
0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hPipe==INVALID_HANDLE_VALUE)
{
MessageBox("Failed to open named pipe!");
hPipe=NULL;
return;
}
其中UT爲服務器主機名。以上兩個程序是照孫鑫的《VC++深刻詳解》抄的。
把這兩個程序都放在同一個機子上能夠通訊。但放在局域網的兩個主機上就不能通訊了,請問爲何?錯在哪?
------解決方案--------------------
看彷佛否有防火牆等攔截..
------解決方案--------------------
代碼彷佛沒看出什麼問題
------解決方案--------------------
我試驗的結果是,若是直接連,極可能連不上,
但若是你用 win鍵 + R ,而後輸入目標機器地址,手動鏈接到目標機器上
而後再運行程序就能夠連上了
------解決方案--------------------
先與目標機器創建IPC鏈接試試看
一種辦法是在程序中執行命令
net use \\ip\\ipc$ password /user:user
user和password是你用於訪問的用戶名和密碼
另外一種辦法是用下面的程序創建IPC鏈接
C/C++ code
BOOL ConnetIPC(char * RemoteName,char * User,char * PassWord)
{
char tmp[128]="\\\\";
strcat(tmp,RemoteName);
strcat(tmp,"\\ipc$");
NETRESOUCE NetResouce;
NetResouce.lpRemoteName=tmp;
NetResouce.dwType=RESOURCETYPE_ANY;
NetResouce.lpProvider=NULL;
if (WnetAddConnection2(&NetResouce,PassWord,User,FLASE)==NO_ERROR)
//創建鏈接!
return FALSE;
else
return TRUE;
}
------解決方案--------------------
C/C++ code
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
if( InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) )
{
// add a NULL disc. ACL to the
// security descriptor.
if (SetSecurityDescriptorDacl(&sd, TRUE, (PACL) NULL, FALSE))
{
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor =&sd;
sa.bInheritHandle = TRUE;
//在這裏
CreateNamedPipe(.......&sa);
}
}