By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,793 Members | 1,252 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,793 IT Pros & Developers. It's quick & easy.

Reusing a local address/port when creating sockets that send data

P: n/a
Hello,

I want to periodically send a TCP packet to a peer, always from the same
source port. That is, each packet will come from my local ip address, port
8801, and go to the peer's ip address, to HIS port 8801.

This means that I need to bind my sender socket to (myaddress,8801), use it
for the send, then shut it down and close it. Then I want to wait, say 30
seconds, and do it all over again. Naturally, the socket's ReuseAddress
property must be set for this to work.

However, in practice, the second time I bind a socket to my local endpoint,
I get a SocketException: "Only one usage of each socket address
(protocol/network address/port) is normally permitted."

Can anyone help me? The following code attempts to send a string containing
the date/time to a server on 192.168.2.10:8810. If I set the "bindIt"
variable to false, the code works fine. If I try to bind (and re-bind) the
socket to the same local endpoint (e.g, I've set bindIt to true), the code
fails with the above exception. Help!

Thanks

Greg Hassett

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class TcpClientTest
{
static public void Main()
{
bool bindIt = true;

IPHostEntry localHostEntry = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint localIPEndPoint = new IPEndPoint
(localHostEntry.AddressList[0], 8801);

while (true)
{
try
{
Console.WriteLine("Press return to send data");
Console.ReadLine();

Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

socket.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1);
socket.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.Linger, new LingerOption(false, 0));
socket.SetSocketOption (SocketOptionLevel.Socket,
SocketOptionName.DontLinger, 1);

if (bindIt)
{
socket.Bind (new IPEndPoint (IPAddress.Any, 8801));
}

socket.Connect (new
IPEndPoint(IPAddress.Parse("192.168.2.10"), 8801));

byte[] buf = Encoding.ASCII.GetBytes
(DateTime.Now.ToString());
socket.Send (buf);

socket.Shutdown (SocketShutdown.Both);
socket.Close ();

Console.Out.WriteLine ("Sent");
}
catch (Exception ex)
{
Console.Out.WriteLine (ex.ToString());
}
}
}
}

Nov 17 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.