C# - error- An attempt was made to access a socket in a way forbidden by its access permissions

Posted on 2012-09-06
Last Modified: 2012-09-11
I have the following error when i run this code, not sure how to fix it...
    Page.Title = "Create an account";
    var sql = string.Empty;
    var firstname = Request["firstname"];
    var lastname = Request["lastname"];
    var username = Request["username"];
    var password = Request["password"];
    var email = Request["email"];
    var email2 = Request["email2"];
            ModelState.AddError("firstname", "Please provide a first name");
            ModelState.AddError("lastname", "Please provide a last name");
            ModelState.AddError("username", "You must provide a user name");
            ModelState.AddError("password", "You must provide a password");
            ModelState.AddError("email", "Please provide your email address");
        if(!email.IsEmpty() && !Functions.IsValidEmail(email)){
            ModelState.AddError("email", "Please provide a valid email address");
        if(email2 != email){
            ModelState.AddError("email2", "Your email addresses must match");
            ModelState.AddFormError("Please fix the errors below before resubmitting the form");
            var db = Database.Open("Classifieds");
            var user = new {FirstName = firstname, LastName = lastname, Email = email};
                var token = WebSecurity.CreateUserAndAccount(username, password, user, true);
                var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
                var message = "<p>Your confirmation code is: " + token + "</p>" +
                    "<p>Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a>" + 
                    " to activate your account.</p>";
                            to: email,	
                            subject: "Please confirm your account", 
                            body: message,
                            isBodyHtml: true
                Roles.AddUsersToRoles(new[]{username}, new[]{"Seller"});
            catch(MembershipCreateUserException ex){
                if(ex.StatusCode == MembershipCreateStatus.DuplicateUserName){
                    ModelState.AddError("username", "That user name is already in use. Please choose another.");
                    ModelState.AddFormError("Please fix the errors below before resubmitting the form");
                    ModelState.AddFormError("Something went wrong. Please try again");
<h2>Create an account</h2>
<p>Use the form below to create an account with the site. Then you can post items for sale and bid on other items. Please ensure that you complete all fields marked with an asterisk *</p>
<form method="post">
            <label for="firstname">First Name*</label>
            <input type="text" id="firstname" name="firstname" value="@firstname" />
            <label for="lastname">Last Name*</label>
            <input type="text" id="lastname" name="lastname" value="@lastname" />
            <label for="username">User Name*</label>
            <input type="text" id="username" name="username" value="@username" />
            <label for="password">Password*</label>
            <input type="password" id="password" name="password" />
            <label for="email">Email*</label>
            <input type="text" id="email" name="email" value="@email" />
            <label for="email2">Re-enter your email*</label>
            <input type="text" id="email2" name="email2" value="@email2" />
            <input type="submit" name="Submit" value="Register" />

Open in new window

Server Error in '/' Application.
An attempt was made to access a socket in a way forbidden by its access permissions
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

Source Error:

Line 43:                     "<p>Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a>" +
Line 44:                     " to activate your account.</p>";
Line 45:                 WebMail.Send(
Line 46:                             to: email,      
Line 47:                             subject: "Please confirm your account",

Source File: c:\webmatrix\Final Code\Chapter12\Classifieds\Account\Register.cshtml    Line: 45

Stack Trace:

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +251
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +279

[WebException: Unable to connect to the remote server]
   System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +6131904
   System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +314
   System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
   System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +322
   System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +146
   System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) +222
   System.Net.Mail.SmtpClient.GetConnection() +50
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1496

[SmtpException: Failure sending mail.]
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1829
   System.Web.Helpers.WebMail.Send(String to, String subject, String body, String from, String cc, IEnumerable`1 filesToAttach, Boolean isBodyHtml, IEnumerable`1 additionalHeaders) +617
   ASP._Page_Account_Register_cshtml.Execute() in c:\webmatrix\Final Code\Chapter12\Classifieds\Account\Register.cshtml:45
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +68
   System.Web.WebPages.WebPage.ExecutePageHierarchy() +156
   System.Web.WebPages.StartPage.RunPage() +19
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContext context) +249
Question by:yguyon28
    LVL 55

    Accepted Solution

    This is normally a firewall problem. As a first dirty test, disable your firewall and run your application; then restore it asap. If this is the problem, insert a firewall rule for the conflicting TCP port.

    Author Closing Comment

    It was actually a web config issue... Weird....

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now