Write to mailslot on remote computer using Delphi

1k views Asked by At

I have read everything I can find about mailslots and am still left with the problem of writing to a mailslot that has been opened for reading by a mailslot server on another computer.

I do not have an issue with mailslots on the same computer. For example, if I try to write to a mailslot on the local computer like this:

var
  sMsg: string;
  iBytes: DWORD;
begin
  SlotName := '\\.\mailslot\testslot';
  Handle := CreateFile(PChar(SlotName), GENERIC_WRITE, FILE_SHARE_READ, nil,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  Result := WriteFile(Handle, sMsg[1], Length(sMsg), iBytes, nil);
end;

CreateFile will fail with file does not exist error code if the mailslot server program has not created the mailslot.

However, if I pass something like this \\MYSERVER\mailslot\testslot as the mailslot name, it always returns a valid file handle. Even if the computer name is not valid, it still returns a file handle and then the WriteFile also succeeds.

I was hoping to have CreateFile fail if either the computername is incorrect or the mailslot server on that computer had not created the mailslot, but this does not seem to be the case, it only seems to be the case when writing to mailslot on the local computer.

Can someone enlighten me ?

1

There are 1 answers

0
Remy Lebeau On BEST ANSWER

The CreateFile() documentation states:

Mailslots

If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function.

That implies that CreateFile() is not able to validate the existence of a remote mailslot, only a local mailslot. Which is consistent with the behavior you are seeing. Windows can easily validate if a local mailslot exists, but cannot validate if a remote mailslot exists. This makes sense when you take into account that mailslots are implemented using datagrams (aka, UDP). UDP has no way of knowing whether a remote destination exists or not. All it can do is put a packet on the network and hope it reaches its destination. This is stated as nuch in the Mailslot documentation:

One important consideration is that mailslots broadcast messages using datagrams. A datagram is a small packet of information that the network sends along the wire. Like a radio or television broadcast, a datagram offers no confirmation of receipt; there is no way to guarantee that a datagram has been received. Just as mountains, large buildings, or interfering signals might cause a radio or television signal to get lost, there are things that can prevent a datagram from reaching a particular destination.

That is why CreateFile() and WriteFile() do not fail when a remote mailslot does not exist. They simply do not know one way or the other.