468,768 Members | 1,657 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,768 developers. It's quick & easy.

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

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
0 2256

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by D. André Dhondt | last post: by
2 posts views Thread by Marty | last post: by
7 posts views Thread by Sharon | last post: by
2 posts views Thread by jasonsgeiger | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.